<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) {
    console.log(req.params);
    console.log("group create started")
    console.log("POST " + req.params.groupname)
    var 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) {
        console.log("next then")
        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) {
        console.log("then cypher query")
        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(id) {
        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
            console.log("next cypher query")
            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) {
        console.log("insert node")
        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) {
        console.log("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);
        })
    }).then(function() {
        console.log("next cypher query")
        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) {
        console.log("next relationship")
        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);
            return relationship._id
        })
    }).then(function(id) {
        console.log("create doc")
        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) {
        console.log("insert couch 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')
            res.send(201, {
                Group: req.params
            });
            res.end();
        });
    })
};
getRequest = function(url) {
    // set up initial get request.
    console.log("start of promise")
    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
            })
        })
    });
}
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 = "",
        db = new neo4j('http://localhost:7474');
    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) {
                console.log("in first then")
                if(call.statusCode === 200) {
                    console.log("in 200")
                    return next(new restify.ConflictError('Group Already Created'));
                }
                console.log("not in 200")
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    console.log("in the cypher request")
                    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(id) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    console.log("in next cypher request")
                    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) {
                console.log("db insert")
                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) {
                console.log("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);
                })
            }).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(id, 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);
                    return relationship._id
                })
            }).then(function(id) {
                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.
            console.log("get promise started")
            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)
                    if(body) {
                        resolve(response)
                    }
                })
            });
        },
        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>missed a variable<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) {
    console.log(req.params);
    console.log("group create started")
    console.log("POST " + req.params.groupname)
    var 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) {
        console.log("next then")
        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) {
        console.log("then cypher query")
        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(id) {
        db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
            console.log("next cypher query")
            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) {
        console.log("insert node")
        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) {
        console.log("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);
        })
    }).then(function() {
        console.log("next cypher query")
        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) {
        console.log("next relationship")
        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);
            return relationship._id
        })
    }).then(function(id) {
        console.log("create doc")
        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) {
        console.log("insert couch 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')
            res.send(201, {
                Group: req.params
            });
            res.end();
        });
    })
};
getRequest = function(url) {
    // set up initial get request.
    console.log("start of promise")
    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
            })
        })
    });
}
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 = "",
        db = new neo4j('http://localhost:7474');
    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) {
                console.log("in first then")
                if(call.statusCode === 200) {
                    console.log("in 200")
                    return next(new restify.ConflictError('Group Already Created'));
                }
                console.log("not in 200")
                db.cypherQuery(" MATCH (n:competition) WHERE n.name ='" + competition + "' RETURN n", function(err, result) {
                    console.log("in the cypher request")
                    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(id) {
                db.cypherQuery("MATCH (n:group) WHERE n.name ='" + groupname + "' RETURN n", function(err, results) {
                    console.log("in next cypher request")
                    if(err) throw err;
                    if(results.data.length == 0) {
                        return results.data
                    } else {
                        console.log(results.data[0])
                        return next(new restify.ConflictError('Group already created'));
                    }
                })
            }).then(function(data) {
                console.log("db insert")
                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) {
                console.log("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);
                    return relationship._id
                })
            }).then(function(id) {
                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(id, 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);
                    return relationship._id
                })
            }).then(function(id) {
                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.
            console.log("get promise started")
            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)
                    if(body) {
                        resolve(response)
                    }
                })
            });
        },
        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>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>. Yo Jekyll!
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var yeomanConfig = {
  app: 'app',
  dist: 'dist'
};

module.exports = function (grunt) {

  // Configuration
  grunt.initConfig({
    yeoman: yeomanConfig,

    watch: {<% if (cssPre === 'sass') { %>
      sass: {
        files: ['<%%= yeoman.app %>/<%= cssPreDir %>/**/*.{scss,sass}'],
        tasks: ['sass:server']
      },<% } %><% if (cssPre === 'compass') { %>
      compass: {
        files: ['<%%= yeoman.app %>/<%= cssPreDir %>/**/*.{scss,sass}'],
        tasks: ['compass:server'<% if (autoPre) { %>, 'autoprefixer:server'<% } %>]
      },<% } %><% if (autoPre) { %>
      stageCss: {
        files: ['<%%= yeoman.app %>/<%= cssDir %>/**/*.css'],
        tasks: ['copy:stageCss', 'autoprefixer:server']
      },<% } %><% if (jsPre === 'coffeescript') { %>
      coffee: {
        files: ['<%%= yeoman.app %>/<%= jsPreDir %>/**/*.coffee'],
        tasks: ['coffee:server']
      },
      coffeeTest: {
        files: ['test/spec/**/*.coffee'],
        tasks: ['coffee:test']
      },<% } %>
      jekyll: {
        files: ['<%%= yeoman.app %>/**/*.{html,yml,md,mkd,markdown}',
                '!<%%= yeoman.app %>/bower_components'],
        tasks: ['jekyll:server']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '.jekyll/**/*.html',<% if (autoPre) { %>
          '.tmp/<%= cssDir %>/**/*.css',<% } else { %>
          '{.tmp,<%%= yeoman.app %>}/<%= cssDir %>/**/*.css',<% } %>
          '{.tmp,<%%= yeoman.app %>}/<%%= js %>/**/*.js',
          '<%%= yeoman.app %>/<%= imgDir %>/**/*.{gif,jpg,jpeg,png,svg,webp}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change hostname to null to access the server from outside.
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, '.jekyll'),
              mountFolder(connect, yeomanConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'test')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, yeomanConfig.dist)
            ];
          }
        }
      }
    },
    open: {
      server: {
        path: 'http://localhost:<%%= connect.options.port %>'
      }
    },
    // Running Jekyll also cleans all non-git files from the target directory
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%%= yeoman.dist %>/*',
            '!<%%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: ['.tmp', '.jekyll']
    },<% if (cssPre === 'sass') { %>
    sass: {
      options: {
        bundleExec: true,
        debugInfo: false,
        lineNumbers: false,
        loadPath: 'app/bower_components'
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= cssPreDir %>',
          src: '**/*.{scss,sass}',
          dest: '.tmp/<%= cssDir %>',
          filter: 'isFile',
          ext: '.css'
        }]
      },
      server: {
        options: {
          debugInfo: true,
          lineNumbers: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= cssPreDir %>',
          src: '**/*.{scss,sass}',
          dest: '.tmp/<%= cssDir %>',
          filter: 'isFile',
          ext: '.css'
        }]
      }
    },<% } %><% if (cssPre === 'compass') { %>
    compass: {
      options: {
        // If you're using global Sass gems, require them here, e.g.:
        // require: ['singularity', 'jacket'],
        bundleExec: true,
        sassDir: '<%%= yeoman.app %>/<%= cssPreDir %>',
        cssDir: '.tmp/<%= cssDir %>',
        imagesDir: '<%%= yeoman.app %>/<%= imgDir %>',
        fontsDir: '<%%= yeoman.app %>/<%= fontsDir %>',
        javascriptsDir: '<%%= yeoman.app %>/<%= jsDir %>',
        relativeAssets: false,
        httpImagesPath: '/<%= imgDir %>',
        httpGeneratedImagesPath: '/<%= imgDir %>/generated',
        outputStyle: 'expanded',
        raw: 'asset_cache_buster :none \nextensions_dir = "<%%= yeoman.app %>/bower_components"\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%%= yeoman.dist %>/<%= imgDir %>/generated'
        }
      },
      server: {
        options: {
          debugInfo: true,
          generatedImagesDir: '.tmp/<%= imgDir %>/generated'
        }
      }
    },<% } %><% if (autoPre) { %>
    autoprefixer: {
      options: {
        browsers: ['last 2 versions']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>/<%= cssDir %>',
          src: '**/*.css',
          dest: '<%%= yeoman.dist %>/<%= cssDir %>'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '.tmp/<%= cssDir %>',
          src: '**/*.css',
          dest: '.tmp/<%= cssDir %>'
        }]
      }
    },<% } %><% if (jsPre === 'coffeescript') { %>
    coffee: {
      test: {
        files: [{
          expand: true,
          cwd: 'test/spec',
          src: '**/*.coffee',
          dest: '.tmp/spec',
          ext: '.js'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= jsPreDir %>',
          src: '**/*.coffee',
          dest: '.tmp/<%= jsDir %>',
          ext: '.js'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= jsPreDir %>',
          src: '**/*.coffee',
          dest: '.tmp/<%= jsDir %>',
          ext: '.js'
        }]
      }
    },<% } %>
    jekyll: {
      // TODO: switch config to options style after
      // https://github.com/dannygarcia/grunt-jekyll/pull/14
      dist: {
        bundleExec: true,
        src : '<%%= yeoman.app %>',
        dest: '<%%= yeoman.dist %>',
        server : false,
        auto : false,
        config: '_config.yml,_config.build.yml'
      },
      server: {
        bundleExec: true,
        src : '<%%= yeoman.app %>',
        dest: '.jekyll',
        server : false,
        auto : false,
        config: '_config.yml'
      }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '{.tmp,<%%= yeoman.app %>}/<%= jsDir %>/**/*.js',
        'test/spec/**/*.js',
        '!<%%= yeoman.app %>/<%= jsDir %>/vendor/**/*',
        '!<%%= yeoman.app %>/bower_components/**/*'
      ],
      report: [
        '{.tmp,<%%= yeoman.app %>}/<%= jsDir %>/**/*.js',
        '!<%%= yeoman.app %>/<%= jsDir %>/vendor/**/*'
      ]
    },
    csscss: {
      options: {
        bundleExec: true,
        minMatch: 2,<% if (cssPre === 'compass' || cssPre === 'sass') { %>
        ignoreSassMixins: false,<% } %><% if (cssPre === 'compass') { %>
        compass: true,<% } %><% if (!cssPre) { %>
        showParserErrors: true,<% } %>
        colorize: true,
        shorthand: false,
        verbose: true
      },
      // Add files to be tested here
      report: {
       src: ['<%%= yeoman.app %>/<%= cssDir %>/**/*.css'<% if (cssPre === 'compass' || cssPre === 'sass') { %>,
             '<%%= yeoman.app %>/<%= cssPreDir %>/**/*.scss'<% } %>]
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      report: {
        src: ['{.tmp,<%%= yeoman.app %>}/<%= cssDir %>/**/*.css']
      }
    },
    // UseminPrepare will only scan one page for usemin blocks. If you have
    // usemin blocks that aren't used in index.html, create a usemin manifest
    // page (hackery!) and point this task there.
    useminPrepare: {
      options: {
        dest: '<%%= yeoman.dist %>'
      },
      html: '<%%= yeoman.dist %>/index.html'
    },
    usemin: {
      options: {
          basedir: '<%%= yeoman.dist %>',
          dirs: ['<%%= yeoman.dist %>/**/*']
      },
      html: ['<%%= yeoman.dist %>/**/*.html'],
      css: ['<%%= yeoman.dist %>/<%= cssDir %>/**/*.css']
    },
    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.html',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    // Usemin adds files to concat
    concat: {},
    // Usemin adds files to uglify
    uglify: {},
    // Usemin adds files to cssmin
    cssmin: {
      dist: {
        options: {
          report: 'gzip'
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          progressive: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.{jpg,jpeg,png}',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.svg',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          src: [
            // Jekyll moves all html and text files
            // Usemin moves css and js files with concat
            // If your site requires it, add other file type patterns here
            // e.g., Bower components that aren't in a usemin block:
            <% if (!h5bpJs) { %>// <% } %>'bower_components/jquery.min.js',
            // Copy moves asset files and directories
            '*.{ico,png}',
            '<%= jsDir %>/**/*',
            '<%= cssDir %>/**/*',
            '<%= imgDir %>/**/*',
            '<%= fontsDir %>/**/*'
          ],
          dest: '<%%= yeoman.dist %>'
        }]
      },
      // Stage assets in case we need them for concatination
      stageCss: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>/<%= cssDir %>',
          src: '**/*.css',
          dest: '.tmp/<%= cssDir %>'
        }]
      },
      stageJs: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>/<%= jsDir %>',
          src: '**/*.js',
          dest: '.tmp/<%= jsDir %>'
        }]
      },
      stageComponents: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          src: 'bower_components/**/*.{css,js}',
          dest: '.tmp/'
        }]
      }
    },
    rev: {
      options: {
        length: 4
      },
      dist: {
        files: {
          src: [
            '<%%= yeoman.dist %>/<%= jsDir %>/**/*.js',
            '<%%= yeoman.dist %>/<%= cssDir %>/**/*.css',
            '<%%= yeoman.dist %>/<%= imgDir %>/**/*.{gif,jpg,jpeg,png,svg,webp}',
            '<%%= yeoman.dist %>/<%= fontsDir %>/**/*.{eot*,svg,ttf,woff}'
          ]
        }
      }
    },
    concurrent: {
      server: [<% if (cssPre === 'sass') { %>
        'sass:server',<% } %><% if (cssPre === 'compass') { %>
        'compass:server',<% } %><% if (jsPre === 'coffeescript') { %>
        'coffee:server',<% } %><% if (autoPre) { %>
        'copy:stageCss',<% } %>
        'jekyll:server'
      ],
      dist: [<% if (cssPre === 'sass') { %>
        'sass:dist',<% } %><% if (cssPre === 'compass') { %>
        'compass:dist',<% } %><% if (jsPre === 'coffeescript') { %>
        'coffee:dist',<% } %>
        'copy:dist',
        'copy:stageCss',
        'copy:stageJs',
        'copy:stageComponents'
      ]
    }
  });

  // Load plugins
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // Define Tasks
  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',<% if (autoPre) { %>
      'autoprefixer:server',<% } %>
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  // No real tests yet. Add your own.
  // grunt.registerTask('test', [
  //   'clean:server',
  //   'concurrent:test',
  //   'connect:test'
  // ]);

  grunt.registerTask('report', [
    'clean:server',<% if (cssPre === 'sass') { %>
    'sass:server',<% } %><% if (cssPre === 'compass') { %>
    'compass:server',<% } %><% if (jsPre === 'coffeescript') { %>
    'coffee:server',<% } %>
    'jshint:report',
    'csscss:report',
    'csslint:report'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    // Jekyll cleans all non-git files from the target directory, so must run first
    'jekyll:dist',
    'concurrent:dist',
    'useminPrepare',
    'concat',<% if (autoPre) { %>
    'autoprefixer:dist',<% } %>
    'cssmin',
    'uglify',
    'imagemin',
    'svgmin',
    'rev',
    'usemin',
    'htmlmin'
    ]);

  grunt.registerTask('default', [
    'report',
    'build'
  ]);
};
<commit_msg>Add directory reference comment<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>. Yo Jekyll!
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};
var yeomanConfig = {
  app: 'app',
  dist: 'dist'
};

// Directory reference
//   css: <%= cssDir %><% if (cssPre) { %>
//   <%= cssPre %>: <%= cssPreDir %><% } %>
//   javascript: <%= jsDir %><% if (jsPre) { %>
//   <%= jsPre %>: <%= jsPreDir %><% } %>
//   images: <%= imgDir %>
//   fonts: <%= fontsDir %>

module.exports = function (grunt) {

  // Configuration
  grunt.initConfig({
    yeoman: yeomanConfig,

    watch: {<% if (cssPre === 'sass') { %>
      sass: {
        files: ['<%%= yeoman.app %>/<%= cssPreDir %>/**/*.{scss,sass}'],
        tasks: ['sass:server']
      },<% } %><% if (cssPre === 'compass') { %>
      compass: {
        files: ['<%%= yeoman.app %>/<%= cssPreDir %>/**/*.{scss,sass}'],
        tasks: ['compass:server'<% if (autoPre) { %>, 'autoprefixer:server'<% } %>]
      },<% } %><% if (autoPre) { %>
      stageCss: {
        files: ['<%%= yeoman.app %>/<%= cssDir %>/**/*.css'],
        tasks: ['copy:stageCss', 'autoprefixer:server']
      },<% } %><% if (jsPre === 'coffeescript') { %>
      coffee: {
        files: ['<%%= yeoman.app %>/<%= jsPreDir %>/**/*.coffee'],
        tasks: ['coffee:server']
      },
      coffeeTest: {
        files: ['test/spec/**/*.coffee'],
        tasks: ['coffee:test']
      },<% } %>
      jekyll: {
        files: ['<%%= yeoman.app %>/**/*.{html,yml,md,mkd,markdown}',
                '!<%%= yeoman.app %>/bower_components'],
        tasks: ['jekyll:server']
      },
      livereload: {
        options: {
          livereload: LIVERELOAD_PORT
        },
        files: [
          '.jekyll/**/*.html',<% if (autoPre) { %>
          '.tmp/<%= cssDir %>/**/*.css',<% } else { %>
          '{.tmp,<%%= yeoman.app %>}/<%= cssDir %>/**/*.css',<% } %>
          '{.tmp,<%%= yeoman.app %>}/<%%= js %>/**/*.js',
          '<%%= yeoman.app %>/<%= imgDir %>/**/*.{gif,jpg,jpeg,png,svg,webp}'
        ]
      }
    },
    connect: {
      options: {
        port: 9000,
        // Change hostname to null to access the server from outside.
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, '.jekyll'),
              mountFolder(connect, yeomanConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, '.tmp'),
              mountFolder(connect, 'test')
            ];
          }
        }
      },
      dist: {
        options: {
          middleware: function (connect) {
            return [
              mountFolder(connect, yeomanConfig.dist)
            ];
          }
        }
      }
    },
    open: {
      server: {
        path: 'http://localhost:<%%= connect.options.port %>'
      }
    },
    // Running Jekyll also cleans all non-git files from the target directory
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%%= yeoman.dist %>/*',
            '!<%%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: ['.tmp', '.jekyll']
    },<% if (cssPre === 'sass') { %>
    sass: {
      options: {
        bundleExec: true,
        debugInfo: false,
        lineNumbers: false,
        loadPath: 'app/bower_components'
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= cssPreDir %>',
          src: '**/*.{scss,sass}',
          dest: '.tmp/<%= cssDir %>',
          filter: 'isFile',
          ext: '.css'
        }]
      },
      server: {
        options: {
          debugInfo: true,
          lineNumbers: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= cssPreDir %>',
          src: '**/*.{scss,sass}',
          dest: '.tmp/<%= cssDir %>',
          filter: 'isFile',
          ext: '.css'
        }]
      }
    },<% } %><% if (cssPre === 'compass') { %>
    compass: {
      options: {
        // If you're using global Sass gems, require them here, e.g.:
        // require: ['singularity', 'jacket'],
        bundleExec: true,
        sassDir: '<%%= yeoman.app %>/<%= cssPreDir %>',
        cssDir: '.tmp/<%= cssDir %>',
        imagesDir: '<%%= yeoman.app %>/<%= imgDir %>',
        fontsDir: '<%%= yeoman.app %>/<%= fontsDir %>',
        javascriptsDir: '<%%= yeoman.app %>/<%= jsDir %>',
        relativeAssets: false,
        httpImagesPath: '/<%= imgDir %>',
        httpGeneratedImagesPath: '/<%= imgDir %>/generated',
        outputStyle: 'expanded',
        raw: 'asset_cache_buster :none \nextensions_dir = "<%%= yeoman.app %>/bower_components"\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%%= yeoman.dist %>/<%= imgDir %>/generated'
        }
      },
      server: {
        options: {
          debugInfo: true,
          generatedImagesDir: '.tmp/<%= imgDir %>/generated'
        }
      }
    },<% } %><% if (autoPre) { %>
    autoprefixer: {
      options: {
        browsers: ['last 2 versions']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>/<%= cssDir %>',
          src: '**/*.css',
          dest: '<%%= yeoman.dist %>/<%= cssDir %>'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '.tmp/<%= cssDir %>',
          src: '**/*.css',
          dest: '.tmp/<%= cssDir %>'
        }]
      }
    },<% } %><% if (jsPre === 'coffeescript') { %>
    coffee: {
      test: {
        files: [{
          expand: true,
          cwd: 'test/spec',
          src: '**/*.coffee',
          dest: '.tmp/spec',
          ext: '.js'
        }]
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= jsPreDir %>',
          src: '**/*.coffee',
          dest: '.tmp/<%= jsDir %>',
          ext: '.js'
        }]
      },
      server: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.app %>/<%= jsPreDir %>',
          src: '**/*.coffee',
          dest: '.tmp/<%= jsDir %>',
          ext: '.js'
        }]
      }
    },<% } %>
    jekyll: {
      // TODO: switch config to options style after
      // https://github.com/dannygarcia/grunt-jekyll/pull/14
      dist: {
        bundleExec: true,
        src : '<%%= yeoman.app %>',
        dest: '<%%= yeoman.dist %>',
        server : false,
        auto : false,
        config: '_config.yml,_config.build.yml'
      },
      server: {
        bundleExec: true,
        src : '<%%= yeoman.app %>',
        dest: '.jekyll',
        server : false,
        auto : false,
        config: '_config.yml'
      }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: [
        'Gruntfile.js',
        '{.tmp,<%%= yeoman.app %>}/<%= jsDir %>/**/*.js',
        'test/spec/**/*.js',
        '!<%%= yeoman.app %>/<%= jsDir %>/vendor/**/*',
        '!<%%= yeoman.app %>/bower_components/**/*'
      ],
      report: [
        '{.tmp,<%%= yeoman.app %>}/<%= jsDir %>/**/*.js',
        '!<%%= yeoman.app %>/<%= jsDir %>/vendor/**/*'
      ]
    },
    csscss: {
      options: {
        bundleExec: true,
        minMatch: 2,<% if (cssPre === 'compass' || cssPre === 'sass') { %>
        ignoreSassMixins: false,<% } %><% if (cssPre === 'compass') { %>
        compass: true,<% } %><% if (!cssPre) { %>
        showParserErrors: true,<% } %>
        colorize: true,
        shorthand: false,
        verbose: true
      },
      // Add files to be tested here
      report: {
       src: ['<%%= yeoman.app %>/<%= cssDir %>/**/*.css'<% if (cssPre === 'compass' || cssPre === 'sass') { %>,
             '<%%= yeoman.app %>/<%= cssPreDir %>/**/*.scss'<% } %>]
      }
    },
    csslint: {
      options: {
        csslintrc: '.csslintrc'
      },
      report: {
        src: ['{.tmp,<%%= yeoman.app %>}/<%= cssDir %>/**/*.css']
      }
    },
    // UseminPrepare will only scan one page for usemin blocks. If you have
    // usemin blocks that aren't used in index.html, create a usemin manifest
    // page (hackery!) and point this task there.
    useminPrepare: {
      options: {
        dest: '<%%= yeoman.dist %>'
      },
      html: '<%%= yeoman.dist %>/index.html'
    },
    usemin: {
      options: {
          basedir: '<%%= yeoman.dist %>',
          dirs: ['<%%= yeoman.dist %>/**/*']
      },
      html: ['<%%= yeoman.dist %>/**/*.html'],
      css: ['<%%= yeoman.dist %>/<%= cssDir %>/**/*.css']
    },
    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeAttributeQuotes: true,
          removeRedundantAttributes: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.html',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    // Usemin adds files to concat
    concat: {},
    // Usemin adds files to uglify
    uglify: {},
    // Usemin adds files to cssmin
    cssmin: {
      dist: {
        options: {
          report: 'gzip'
        }
      }
    },
    imagemin: {
      dist: {
        options: {
          progressive: true
        },
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.{jpg,jpeg,png}',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%%= yeoman.dist %>',
          src: '**/*.svg',
          dest: '<%%= yeoman.dist %>'
        }]
      }
    },
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          src: [
            // Jekyll moves all html and text files
            // Usemin moves css and js files with concat
            // If your site requires it, add other file type patterns here
            // e.g., Bower components that aren't in a usemin block:
            <% if (!h5bpJs) { %>// <% } %>'bower_components/jquery.min.js',
            // Copy moves asset files and directories
            '*.{ico,png}',
            '<%= jsDir %>/**/*',
            '<%= cssDir %>/**/*',
            '<%= imgDir %>/**/*',
            '<%= fontsDir %>/**/*'
          ],
          dest: '<%%= yeoman.dist %>'
        }]
      },
      // Stage assets in case we need them for concatination
      stageCss: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>/<%= cssDir %>',
          src: '**/*.css',
          dest: '.tmp/<%= cssDir %>'
        }]
      },
      stageJs: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>/<%= jsDir %>',
          src: '**/*.js',
          dest: '.tmp/<%= jsDir %>'
        }]
      },
      stageComponents: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%%= yeoman.app %>',
          src: 'bower_components/**/*.{css,js}',
          dest: '.tmp/'
        }]
      }
    },
    rev: {
      options: {
        length: 4
      },
      dist: {
        files: {
          src: [
            '<%%= yeoman.dist %>/<%= jsDir %>/**/*.js',
            '<%%= yeoman.dist %>/<%= cssDir %>/**/*.css',
            '<%%= yeoman.dist %>/<%= imgDir %>/**/*.{gif,jpg,jpeg,png,svg,webp}',
            '<%%= yeoman.dist %>/<%= fontsDir %>/**/*.{eot*,svg,ttf,woff}'
          ]
        }
      }
    },
    concurrent: {
      server: [<% if (cssPre === 'sass') { %>
        'sass:server',<% } %><% if (cssPre === 'compass') { %>
        'compass:server',<% } %><% if (jsPre === 'coffeescript') { %>
        'coffee:server',<% } %><% if (autoPre) { %>
        'copy:stageCss',<% } %>
        'jekyll:server'
      ],
      dist: [<% if (cssPre === 'sass') { %>
        'sass:dist',<% } %><% if (cssPre === 'compass') { %>
        'compass:dist',<% } %><% if (jsPre === 'coffeescript') { %>
        'coffee:dist',<% } %>
        'copy:dist',
        'copy:stageCss',
        'copy:stageJs',
        'copy:stageComponents'
      ]
    }
  });

  // Load plugins
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  // Define Tasks
  grunt.registerTask('server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'concurrent:server',<% if (autoPre) { %>
      'autoprefixer:server',<% } %>
      'connect:livereload',
      'open',
      'watch'
    ]);
  });

  // No real tests yet. Add your own.
  // grunt.registerTask('test', [
  //   'clean:server',
  //   'concurrent:test',
  //   'connect:test'
  // ]);

  grunt.registerTask('report', [
    'clean:server',<% if (cssPre === 'sass') { %>
    'sass:server',<% } %><% if (cssPre === 'compass') { %>
    'compass:server',<% } %><% if (jsPre === 'coffeescript') { %>
    'coffee:server',<% } %>
    'jshint:report',
    'csscss:report',
    'csslint:report'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    // Jekyll cleans all non-git files from the target directory, so must run first
    'jekyll:dist',
    'concurrent:dist',
    'useminPrepare',
    'concat',<% if (autoPre) { %>
    'autoprefixer:dist',<% } %>
    'cssmin',
    'uglify',
    'imagemin',
    'svgmin',
    'rev',
    'usemin',
    'htmlmin'
    ]);

  grunt.registerTask('default', [
    'report',
    'build'
  ]);
};
<|endoftext|>


<commit_before>/*!
 * debug.js
 *
 * Copyright 2016 Takashi Harano
 * Released under the MIT license
 * https://github.com/takashiharano/debug.js
 *
 * Date: 2016-03-16T23:11+09:00
 */
function DebugJS() {
  this.ENABLE = true;
  this.DEFAULT_SHOW = true;

  this.DEFAULT_OPTIONS = {
    'buffSize': 20,
    'width': 450,
    'top': 25,
    'right': 30,
    'errorColor': '#d44',
    'warnColor': '#ed0',
    'infoColor': '#fff',
    'debugColor': '#8cf',
    'verboseColor': '#ccc',
    'specialColor': '#0f0',
    'showLineNums': true,
    'showClearButton': true,
    'showCloseButton': true
  };

  this.DEFAULT_STYLE = {
    'position': 'absolute',
    'width': this.DEFAULT_OPTIONS.width + 'px',
    'padding': '0',
    'line-height': '1em',
    'border': 'solid 1px #888',
    'font-family': 'Consolas',
    'font-size': '12px',
    'color': '#fff',
    'background': '#111',
    'display': 'block',
    'z-index': 0x7fffffff,
    'box-shadow': '10px 10px 10px rgba(0,0,0,.3)'
  };

  this.id = null;
  this.msgArea = null;
  this.automode = false;
  this.show = false;
  this.options = null;
  this.DEFAULT_ELM_ID = '_debug_';
}

DebugJS.prototype = {
  init:  function(elmId, options) {
    if(!this.ENABLE){return;}

    if (elmId == null) {
      this.id = this.DEFAULT_ELM_ID;
      this.automode = true;
    } else {
      this.id = elmId;
      this.msgArea = document.getElementById(this.id);
    }

    if (options == null) {
      this.options = this.DEFAULT_OPTIONS;
    } else {
      this.options = options;
    }
    this.show = this.DEFAULT_SHOW;

    if (this.msgArea == null) {
      var div = document.createElement('div');
      div.id = this.id;
      var body = document.getElementsByTagName('body')[0];
      body.appendChild(div);
      this.msgArea = div;
    }

    this.msgBuff = new RingBuffer(this.options.buffSize);

    var selector = '#' + this.id;
    var styles = {};
    styles[selector] = this.DEFAULT_STYLE;

    if (this.automode) {
      var wkStyle = styles[selector];
      wkStyle.position = 'fixed';
      wkStyle.width = this.options.width + 'px';
      wkStyle.top = this.options.top  + 'px';
      wkStyle.left = (window.innerWidth - this.options.width - this.options.right) + 'px';
      wkStyle.background = 'rgba(0,0,0,0.7)';
      if (!this.show) {
        wkStyle.display = 'none';
      }
    }

    selector = '#' + this.id + ' a';
    styles[selector] = {'color': '#00bfff'};
    this.applyStyles(styles);

    this.clearMessage();

    if (this.automode) {
      this.setupMove();
      this.setupKeyHandler();
    }
  },

  isInitialized: function() {
    if (this.msgArea == null) {
      return false;
    } else {
      return true;
    }
  },

  printMessage: function() {
    var buf = this.msgBuff.getAll();
    var msg = '';
    msg += '
';
    if (this.options.showClearButton) {
      msg += '[clear]';
    }

    if (this.options.showCloseButton) {
      msg += '×';
    }
    msg += '
';

    msg += '
';
    for (var i = 0; i < buf.length; i++) {
      msg += buf[i] + '
';
    }
    msg += '
';
    this.msgArea.innerHTML = msg;
  },

  clearMessage: function() {
    this.msgBuff.clear();
    this.printMessage();
  },

  setStyle: function(prop, val) {
    var selector = '#' + this.id;
    var styles = {};
    var style = {};
    style[prop] = val;
    styles[selector] = style;
    this.applyStyles(styles);
  },

  applyStyles: function(styles) {
    var styleEl = document.createElement('style');
    document.head.appendChild(styleEl);
    styleEl.appendChild(document.createTextNode(''));
    var s = styleEl.sheet;
    for (var selector in styles) {
      var props = styles[selector];
      var propStr = '';
      for (var propName in props) {
        var propVal = props[propName];
        var propImportant = '';
        if (propVal[1] === true) {
          propVal = propVal[0];
          propImportant = ' !important'
        }
        propStr += propName + ':' + propVal + propImportant + ';\n';
      }
      s.insertRule(selector + '{' + propStr + '}', s.cssRules.length);
    }
  },

  setupMove: function() {
    var el = this.msgArea;
    var dragging;
    var clickOffsetTop;
    var clickOffsetLeft;

    el.onmousedown = function(evt) {
      dragging = true;
      evt = (evt) || window.event;
      clickOffsetTop = evt.clientY - el.offsetTop;
      clickOffsetLeft = evt.clientX - el.offsetLeft;
      if (!document.all) {
         window.getSelection().removeAllRanges();
      }
    }
    el.onmouseup = function() {
      dragging = false;
    }
    el.onmousemove = function(evt) {
      evt = (evt) || window.event;
      if (dragging){
        el.style.top = evt.clientY - clickOffsetTop + 'px';
        el.style.left = evt.clientX - clickOffsetLeft + 'px';
      }
    }
  },

  setupKeyHandler: function() {
    window.addEventListener('keydown', this.keyhandler, false);
  },

  keyhandler: function(e) {
    if (e.keyCode == 113) {
      // F2
      if (Debug.show) {
        Debug.hideDebugWindow();
      } else {
        Debug.showDebugWindow();
      }
    } else if (e.keyCode == 27) {
      // ESC
      Debug.hideDebugWindow();
    }
  },

  hideDebugWindow: function() {
    var selector = '#' + Debug.id;
    var styles = {};
    styles[selector] = {'display': 'none'};
    Debug.applyStyles(styles);
    Debug.show = false;
  },

  showDebugWindow: function() {
    var selector = '#' + Debug.id;
    var styles = {};
    styles[selector] = {'display': 'block'};
    Debug.applyStyles(styles);
    Debug.show = true;
  }
};

var RingBuffer = function(bufferSize) {
  if (bufferSize == undefined) {
    bufferSize = 0;
  }
  this.buffer = new Array(bufferSize);
  this.count = 0;
};

RingBuffer.prototype = {
  add: function(data) {
    var lastIndex = (this.count % this.buffer.length);
    this.buffer[lastIndex] = data;
    this.count++;
    return;
  },

  get: function(index) {
    if (this.buffer.length < this.count) {
      index += this.count;
    }
    index %= this.buffer.length;
    return this.buffer[index];
  },

  getAll: function() {
    var allBuff = [];
    var bufCnt = this.count;
    var bufLen = this.buffer.length;
    var padding = '';
    var line = '';
    var msg = '';
    var pos = 0;
    var cnt;

    var maxCnt = bufLen;
    if (bufCnt > this.buffer.length) {
      pos = (bufCnt % this.buffer.length);
      maxCnt = bufCnt;
    }

    for (var i = 0; i < bufLen; i++) {
      if (pos >= bufLen) {
        pos = 0;
      }

      if (bufCnt < bufLen) {
        cnt = i;
      } else {
        cnt = bufCnt - bufLen + i;
      }
      cnt++; //start at 1

      if (Debug.options.showLineNums) {
        var diffDigits = this.digits(maxCnt) - this.digits(cnt);
        padding = '';
        for (var j = 0; j < diffDigits; j++) {
          padding = padding + '0';
        }
        line = padding + cnt + ': ';
      }

      if (this.buffer[pos] == undefined) {
        msg = '';
      } else {
        msg = this.buffer[pos];
      }

      allBuff[i] = line + msg;
      pos++;
    }

    return allBuff;
  },

  clear: function() {
    this.buffer = new Array(this.buffer.length);
    this.count = 0;
    return;
  },

  digits: function(x) {
    var digit = 0;
    while (x != 0) {
      x = (x / 10) << 0;
      digit++;
    }
    return digit;
  }
};

var Debug = new DebugJS();

var log = function(msg) {
  if(!Debug.ENABLE){return;}
  log.init();
  Debug.msgBuff.add(msg);
  Debug.printMessage();
}

log.init = function(msg) {
  if (!Debug.isInitialized()) {
    Debug.init(null, null);
  }
  if (msg) {
    msg = msg.replace(/ /g , ' ');
  }
  return msg;
}

log.e = function(msg) {
  log.init(null);
  var m = '' + msg + '';
  log(m);
}

log.w = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.i = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.d = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.v = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.s = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}
<commit_msg>Update: add time output<commit_after>/*!
 * debug.js
 *
 * Copyright 2016 Takashi Harano
 * Released under the MIT license
 * https://github.com/takashiharano/debug.js
 *
 * Date: 2016-03-18T00:30+09:00
 */
function DebugJS() {
  this.ENABLE = true;
  this.DEFAULT_SHOW = true;

  this.DEFAULT_OPTIONS = {
    'buffSize': 20,
    'width': 480,
    'top': 25,
    'right': 30,
    'errorColor': '#d44',
    'warnColor': '#ed0',
    'infoColor': '#fff',
    'debugColor': '#8cf',
    'verboseColor': '#ccc',
    'specialColor': '#0f0',
    'showLineNums': true,
    'showClearButton': true,
    'showCloseButton': true
  };

  this.DEFAULT_STYLE = {
    'position': 'absolute',
    'width': this.DEFAULT_OPTIONS.width + 'px',
    'padding': '0',
    'line-height': '1em',
    'border': 'solid 1px #888',
    'font-family': 'Consolas',
    'font-size': '12px',
    'color': '#fff',
    'background': '#111',
    'display': 'block',
    'z-index': 0x7fffffff,
    'box-shadow': '10px 10px 10px rgba(0,0,0,.3)'
  };

  this.id = null;
  this.msgArea = null;
  this.automode = false;
  this.show = false;
  this.options = null;
  this.DEFAULT_ELM_ID = '_debug_';
}

DebugJS.getTime = function() {
  var nowDate = new Date();
  var mon = nowDate.getMonth() + 1;
  var day = nowDate.getDate();
  var hour = nowDate.getHours();
  var min = nowDate.getMinutes();
  var sec = nowDate.getSeconds();

  if (mon < 10) mon = '0' + mon;
  if (day < 10) day = '0' + day;
  if (hour < 10) hour = '0' + hour;
  if (min < 10) min = '0' + min;
  if (sec < 10) sec = '0' + sec;

  var dateTime = {
    'year': nowDate.getFullYear(),
    'mon': mon,
    'day': day,
    'hour': hour,
    'min': min,
    'sec': sec,
    'wday': nowDate.getDay()
  }

  return dateTime;
}

DebugJS.time = function() {
  var dt = DebugJS.getTime();
  var tm = dt.hour + ':' + dt.min + ':' + dt.sec;
  return tm;
}

DebugJS.prototype = {
  init:  function(elmId, options) {
    if(!this.ENABLE){return;}

    if (elmId == null) {
      this.id = this.DEFAULT_ELM_ID;
      this.automode = true;
    } else {
      this.id = elmId;
      this.msgArea = document.getElementById(this.id);
    }

    if (options == null) {
      this.options = this.DEFAULT_OPTIONS;
    } else {
      this.options = options;
    }
    this.show = this.DEFAULT_SHOW;

    if (this.msgArea == null) {
      var div = document.createElement('div');
      div.id = this.id;
      var body = document.getElementsByTagName('body')[0];
      body.appendChild(div);
      this.msgArea = div;
    }

    this.msgBuff = new RingBuffer(this.options.buffSize);

    var selector = '#' + this.id;
    var styles = {};
    styles[selector] = this.DEFAULT_STYLE;

    if (this.automode) {
      var wkStyle = styles[selector];
      wkStyle.position = 'fixed';
      wkStyle.width = this.options.width + 'px';
      wkStyle.top = this.options.top  + 'px';
      wkStyle.left = (window.innerWidth - this.options.width - this.options.right) + 'px';
      wkStyle.background = 'rgba(0,0,0,0.7)';
      if (!this.show) {
        wkStyle.display = 'none';
      }
    }

    selector = '#' + this.id + ' a';
    styles[selector] = {'color': '#00bfff'};
    this.applyStyles(styles);

    this.clearMessage();

    if (this.automode) {
      this.setupMove();
      this.setupKeyHandler();
    }
  },

  isInitialized: function() {
    if (this.msgArea == null) {
      return false;
    } else {
      return true;
    }
  },

  printMessage: function() {
    var buf = this.msgBuff.getAll();
    var msg = '';
    msg += '
';
    if (this.options.showClearButton) {
      msg += '[clear]';
    }

    if (this.options.showCloseButton) {
      msg += '×';
    }
    msg += '
';

    msg += '
';
    for (var i = 0; i < buf.length; i++) {
      msg += buf[i] + '
';
    }
    msg += '
';
    this.msgArea.innerHTML = msg;
  },

  clearMessage: function() {
    this.msgBuff.clear();
    this.printMessage();
  },

  setStyle: function(prop, val) {
    var selector = '#' + this.id;
    var styles = {};
    var style = {};
    style[prop] = val;
    styles[selector] = style;
    this.applyStyles(styles);
  },

  applyStyles: function(styles) {
    var styleEl = document.createElement('style');
    document.head.appendChild(styleEl);
    styleEl.appendChild(document.createTextNode(''));
    var s = styleEl.sheet;
    for (var selector in styles) {
      var props = styles[selector];
      var propStr = '';
      for (var propName in props) {
        var propVal = props[propName];
        var propImportant = '';
        if (propVal[1] === true) {
          propVal = propVal[0];
          propImportant = ' !important'
        }
        propStr += propName + ':' + propVal + propImportant + ';\n';
      }
      s.insertRule(selector + '{' + propStr + '}', s.cssRules.length);
    }
  },

  setupMove: function() {
    var el = this.msgArea;
    var dragging;
    var clickOffsetTop;
    var clickOffsetLeft;

    el.onmousedown = function(evt) {
      dragging = true;
      evt = (evt) || window.event;
      clickOffsetTop = evt.clientY - el.offsetTop;
      clickOffsetLeft = evt.clientX - el.offsetLeft;
      if (!document.all) {
         window.getSelection().removeAllRanges();
      }
    }
    el.onmouseup = function() {
      dragging = false;
    }
    el.onmousemove = function(evt) {
      evt = (evt) || window.event;
      if (dragging){
        el.style.top = evt.clientY - clickOffsetTop + 'px';
        el.style.left = evt.clientX - clickOffsetLeft + 'px';
      }
    }
  },

  setupKeyHandler: function() {
    window.addEventListener('keydown', this.keyhandler, false);
  },

  keyhandler: function(e) {
    if (e.keyCode == 113) {
      // F2
      if (Debug.show) {
        Debug.hideDebugWindow();
      } else {
        Debug.showDebugWindow();
      }
    } else if (e.keyCode == 27) {
      // ESC
      Debug.hideDebugWindow();
    }
  },

  hideDebugWindow: function() {
    var selector = '#' + Debug.id;
    var styles = {};
    styles[selector] = {'display': 'none'};
    Debug.applyStyles(styles);
    Debug.show = false;
  },

  showDebugWindow: function() {
    var selector = '#' + Debug.id;
    var styles = {};
    styles[selector] = {'display': 'block'};
    Debug.applyStyles(styles);
    Debug.show = true;
  }
};

var RingBuffer = function(bufferSize) {
  if (bufferSize == undefined) {
    bufferSize = 0;
  }
  this.buffer = new Array(bufferSize);
  this.count = 0;
};

RingBuffer.prototype = {
  add: function(data) {
    var lastIndex = (this.count % this.buffer.length);
    this.buffer[lastIndex] = data;
    this.count++;
    return;
  },

  get: function(index) {
    if (this.buffer.length < this.count) {
      index += this.count;
    }
    index %= this.buffer.length;
    return this.buffer[index];
  },

  getAll: function() {
    var allBuff = [];
    var bufCnt = this.count;
    var bufLen = this.buffer.length;
    var padding = '';
    var line = '';
    var msg = '';
    var pos = 0;
    var cnt;

    var maxCnt = bufLen;
    if (bufCnt > this.buffer.length) {
      pos = (bufCnt % this.buffer.length);
      maxCnt = bufCnt;
    }

    for (var i = 0; i < bufLen; i++) {
      if (pos >= bufLen) {
        pos = 0;
      }

      if (bufCnt < bufLen) {
        cnt = i;
      } else {
        cnt = bufCnt - bufLen + i;
      }
      cnt++; //start at 1

      if (Debug.options.showLineNums) {
        var diffDigits = this.digits(maxCnt) - this.digits(cnt);
        padding = '';
        for (var j = 0; j < diffDigits; j++) {
          padding = padding + '0';
        }
        line = padding + cnt + ': ';
      }

      if (this.buffer[pos] == undefined) {
        msg = '';
      } else {
        msg = this.buffer[pos];
      }

      allBuff[i] = line + msg;
      pos++;
    }

    return allBuff;
  },

  clear: function() {
    this.buffer = new Array(this.buffer.length);
    this.count = 0;
    return;
  },

  digits: function(x) {
    var digit = 0;
    while (x != 0) {
      x = (x / 10) << 0;
      digit++;
    }
    return digit;
  }
};

var Debug = new DebugJS();

var log = function(msg) {
  if(!Debug.ENABLE){return;}
  log.init();
  var t = DebugJS.time();
  msg = t + ' ' + msg;
  Debug.msgBuff.add(msg);
  Debug.printMessage();
}

log.init = function(msg) {
  if (!Debug.isInitialized()) {
    Debug.init(null, null);
  }
  if (msg) {

    msg = msg.replace(/ /g , ' ');
  }
  return msg;
}

log.e = function(msg) {
  log.init(null);
  var m = '' + msg + '';
  log(m);
}

log.w = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.i = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.d = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.v = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}

log.s = function(msg) {
  msg = log.init(msg);
  var m = '' + msg + '';
  log(m);
}
<|endoftext|>