<commit_before>class TaskList {

    constructor() {
        this.tasks = {};
        this.sortField = "priority";
        this.sortDir = "desc";
        this.isSortEnabled = false;

        this.searchTerm = "";
        this.searchObj = {};
        this.searchChildren = false;
        this.searchParents = false;

        this.visibleTasks = {};

        this.path = "";
        this.googleDriveId = undefined;

        this.title = "TaskList";

        this.idForIsolatedTask = undefined;
        this.hideRootIfIsolated = false;

        this.shouldHideComplete = true;

        this._possibleColumns = [
            { "name": "action", "label": "", "datatype": "action", "editable": false, "active": true },
            { "name": "ID", "label": "id", "datatype": "integer,,-1,,,", "editable": false, "active": false },
            { "name": "description", "label": "desc", "datatype": "hashtag", "editable": true, "active": false },
            { "name": "duration", "label": "duration (min)", "datatype": "double", "editable": true, "active": false },
            { "name": "priority", "label": "priority", "datatype": "integer", "editable": true, "active": false },
            { "name": "status", "label": "status", "datatype": "string", "editable": true, "active": false },
            { "name": "tags", "label": "tags", "datatype": "array", "editable": true, "active": false },
            { "name": "milestone", "label": "milestone", "datatype": "string", "editable": true, "active": false },
            { "name": "comments", "label": "comments", "datatype": "string", "editable": true, "active": false },
            { "name": "dateAdded", "label": "added", "datatype": "date", "editable": true, "active": false },
            { "name": "startDate", "label": "start", "datatype": "date", "editable": true, "active": false },
            { "name": "endDate", "label": "end", "datatype": "date", "editable": true, "active": false }
        ]

        this.columns = _.keyBy(this._possibleColumns, "name");
    }

    getAllTags() {
        var tags = [];
        _.each(this.tasks, function (item) {
            _.each(item.tags, function (tag) {
                if (tags.indexOf(tag) == -1) {
                    tags.push(tag);
                }
            })
        })

        tags.sort();

        return tags;
    }

    getAllStatus() {
        var status = [];
        _.each(this.tasks, function (task) {
            if (status.indexOf(task.status) == -1 && task.status != null) {
                status.push(task.status);
            }
        })

        status.sort();

        return status;
    }

    assignStrandedTasksToCurrentIsolationLevel() {
        var self = this;
        _.each(this.tasks, function (task) {
            if (task.parentTask == null && !task.isProjectRoot) {
                task.parentTask = self.idForIsolatedTask;
                self.tasks[self.idForIsolatedTask].childTasks.push(task.ID);
            }
        })
    }

    getProjectsInList() {
        var projects = [];
        _.each(this.tasks, function (task) {
            if (task.isProjectRoot) {
                projects.push(task);
            }
        })

        projects.sort();

        return projects;
    }

    getMilestones() {
        var projects = [];
        _.each(this.tasks, function (task) {
            if (projects.indexOf(task.milestone) == -1 && task.milestone != null) {
                projects.push(task.milestone);
            }
        })

        return projects;
    }

    getCrumbs() {
        //need to return these in top down order

        //get the isolation level, and work up through parents until there is none
        var crumbsOut = [];

        //return an array of tasks
        var bottomTask = this.tasks[this.idForIsolatedTask];

        while (bottomTask != null) {
            crumbsOut.unshift(bottomTask);

            if (bottomTask.parentTask == null) {
                bottomTask = null;
            } else {
                bottomTask = this.tasks[bottomTask.parentTask]
            }
        }

        return crumbsOut;
    }

    getGridDataObject() {
        var gridDataObject = {
            "metadata": _.filter(this.columns, "active"),
            "data": this._processGridData()
        };

        return gridDataObject;
    };

    _processGridData() {
        //get a list of all tasks
        //iterate through them
        //if they have a child... process the child next... same for that child
        //if they have a parent... skip and let the parent find them first

        //all tasks with either be at the root or have a parent
        //if at the root, add to the root, and process the child tasks, just push them on
        //do a depth first seach and all will get added

        var tasksOut = []

        //these checks set the sort column if used
        this.activeSortField = (this.isSortEnabled) ? this.sortField : "sortOrder";
        this.activeSortDir = (this.isSortEnabled) ? this.sortDir : "asc";

        //process the searchTerm
        //split on spaces, split on colon, build object
        //TODO split this out to get the search in a single place
        this.searchObj = this.searchTerm;
        var searchTextParts = this.searchTerm.split(" ");

        var self = this;

        _.each(searchTextParts, function (spaces) {
            if (spaces.indexOf(":") > -1) {
                var parts = spaces.split(":");

                if (typeof self.searchObj !== "object") {
                    self.searchObj = {};
                }
                self.searchObj[parts[0]] = parts[1];
            }
        })

        //run through children to update any dependent properties
        this.getPseudoRootNode().updateDependentProperties();

        //run the searches
        this.determineIfTasksAreVisible();

        //process children
        if (this.idForIsolatedTask == undefined) {
            this.recurseChildren(this.getPseudoRootNode(), -1, tasksOut)
        } else {
            //do the recursion only on the selected task
            var isolatedTask = this.tasks[this.idForIsolatedTask];
            //this will start at -1 (ignored) or 0 depending on flag.
            var startLevel = (this.hideRootIfIsolated) ? -1 : 0;
            this.recurseChildren(isolatedTask, startLevel, tasksOut);
        }

        //need to build tasksout down here based on the task visible option

        return _.map(tasksOut, function (item) {
            return { "id": item.ID, "values": item }
        })
    }

    determineIfTasksAreVisible() {
        //iterate each task and run the search
        var self = this;

        var tasksToProcessAgain = [];
        _.each(this.tasks, function (task) {
            var searchResult = self.searchTerm == "" || task.isResultForSearch(self.searchObj)
            var showBecauseComplete = (self.shouldHideComplete) ? !task.isComplete : true;
            var showBecauseNew = task.isFirstEdit;
            if ((searchResult && showBecauseComplete)||showBecauseNew) {

                tasksToProcessAgain.push(task);
                task.isVisible = true;
            } else {
                task.isVisible = false;
            }
        })

        _.each(tasksToProcessAgain, function (task) {
            if (self.searchChildren) {
                //add the kids
                function recurseMakeVisible(childTask) {
                    _.each(childTask.childTasks, function (childTaskID) {
                        recurseMakeVisible(self.tasks[childTaskID]);
                    })
                    childTask.isVisible = !childTask.isComplete;
                }

                recurseMakeVisible(task);
            }

            if (self.searchParents) {
                //add the parents
                //TODO rename the variables, this is awful
                var parentTaskId = task.parentTask;
                while (parentTaskId != null) {
                    var parentTask = self.tasks[parentTaskId]
                    parentTask.isVisible = !parentTask.isComplete;
                    parentTaskId = parentTask.parentTask;
                }
            }
        })
        //at this point, all of the tasks have visibility set
    }

    recurseChildren(task, indentLevel, tasksOut) {
        //skip if starting on the pseudo root
        if (indentLevel > -1) {
            //do a check on desc
            if (task.isVisible) {
                tasksOut.push(task);
            }
        }
        task.indent = indentLevel;
        var subProcessOrder = 0;

        //determine subtask ordering
        var self = this;
        var subOrder = _.map(task.childTasks, function (childTaskId) {
            return { "sort": self.tasks[childTaskId][self.activeSortField], "id": childTaskId }
        })

        subOrder = _.orderBy(subOrder, ["sort"], [this.activeSortDir])

        _.each(subOrder, function (itemObj) {
            var itemNo = itemObj.id;
            var childTask = self.tasks[itemNo];
            childTask.sortOrder = subProcessOrder++;
            self.recurseChildren(childTask, indentLevel + 1, tasksOut)
        });
    }

    getPseudoRootNode() {
        //need to return a "task" that has the parentless nodes as its children

        var newTask = new Task(this, false);

        _.each(this.tasks, function (task) {
            if (task.parentTask == null) {
                newTask.childTasks.push(task.ID)
            }
        })

        return newTask;
    }

    getNew() {
        var task = new Task(this);
        this.tasks[task.ID] = task;

        return task;
    }

    removeTask(ID) {
        //this will delete the task from the object

        //check if the task has a parent, if so remove from there
        var taskToDelete = this.tasks[ID];

        if (taskToDelete.parentTask != null) {
            //assign children to current parent
            var parentTask = this.tasks[taskToDelete.parentTask];
            parentTask.childTasks = parentTask.childTasks.concat(taskToDelete.childTasks);

            //find the index of the current task and splice it out
            var index = parentTask.childTasks.indexOf(ID);
            parentTask.childTasks.splice(index, 1);
        }

        //update parent of children to current parent
        var obj = this;
        _.each(taskToDelete.childTasks, function (taskId) {
            obj.tasks[taskId].parentTask = taskToDelete.parentTask;
        })

        //check if task has children, if so, delete those children too (and their children)
        // -or- collapse the current node "up" a level into the current parent

        delete this.tasks[ID];
    }

    getListOfColumns() {
        //this will return a list of all possible columns that could be visualized

        //iterate through possible columns and return the name
        return _.map(this._possibleColumns, "name");
    }

    getJSONString() {
        //TODO use this method for the normal save() call too
        var output = _.map(this.tasks, function (d) {
            return d.getObjectForSaving();
        })

        var objectToSave = {
            title: this.title,
            googleDriveId: this.googleDriveId,
            tasks: output
        };

        return JSON.stringify(objectToSave);
    }

    isDefaultList(){
        console.log(this.tasks)
        if(Object.keys(this.tasks).length == 2 && this.tasks[3].description == "new task"){
            return true;
        }

        return false;
    }

    save(callback) {
        var jsonfile = require("jsonfile");
        var _ = require("lodash");

        if (this.path == "") {
            //TODO put this prompt into a actual message bar
            console.log("no path set, will not save");
            return false;
        }

        //create new object with only the date to keep
        var output = _.map(this.tasks, function (d) {
            return d.getObjectForSaving();
        })

        var objectToSave = {
            title: this.title,
            googleDriveId: this.googleDriveId,
            tasks: output
        };

        jsonfile.writeFile(this.path, objectToSave, { spaces: 2 }, function (err) {
            if (err != null) {
                console.error(err);
            }

            //TODO change this out for a status update proper
            console.log("saved... calling callback");
            if (callback !== undefined) {
                callback();
            }
        })

        return true;
    }

    static createNewTaskList() {
        //create the new task list
        var list = new TaskList();

        //create a root task
        var rootTask = list.getNew();
        rootTask.isProjectRoot = true;
        rootTask.description = "new project";

        //isolate to the root task
        list.idForIsolatedTask = rootTask.ID;

        return list;
    }

    static load(path, callback, fileId) {
        var jsonfile = require("jsonfile");

        //create new object with only the date to keep
        var _ = require("lodash");

        var taskList = new TaskList();
        taskList.path = path;

        jsonfile.readFile(taskList.path, function (err, obj) {

            var dataObj = {};

            if (obj.length > 0) {
                //this is for the old format where the file was only tasks
                dataObj.tasks = obj;
            } else {
                //this loads an actual TaskList object
                dataObj = obj;
            }

            //obj contains title, googleDriveId, and tasks
            taskList.title = dataObj.title;
            if (fileId == undefined) {
                //try to get the data from the file
                taskList.googleDriveId = dataObj.googleDriveId;
            } else {
                //grab the fileId from Google
                taskList.googleDriveId = fileId;
            }

            _.each(dataObj.tasks, function (item) {
                var task = Task.createFromData(item, taskList);

                taskList.tasks[task.ID] = task;
            })

            //work is done, call the callback
            callback(taskList);
        })
    }
}

module.exports = TaskList;<commit_msg>Change default conditions for save prompt<commit_after>class TaskList {

    constructor() {
        this.tasks = {};
        this.sortField = "priority";
        this.sortDir = "desc";
        this.isSortEnabled = false;

        this.searchTerm = "";
        this.searchObj = {};
        this.searchChildren = false;
        this.searchParents = false;

        this.visibleTasks = {};

        this.path = "";
        this.googleDriveId = undefined;

        this.title = "TaskList";

        this.idForIsolatedTask = undefined;
        this.hideRootIfIsolated = false;

        this.shouldHideComplete = true;

        this._possibleColumns = [
            { "name": "action", "label": "", "datatype": "action", "editable": false, "active": true },
            { "name": "ID", "label": "id", "datatype": "integer,,-1,,,", "editable": false, "active": false },
            { "name": "description", "label": "desc", "datatype": "hashtag", "editable": true, "active": false },
            { "name": "duration", "label": "duration (min)", "datatype": "double", "editable": true, "active": false },
            { "name": "priority", "label": "priority", "datatype": "integer", "editable": true, "active": false },
            { "name": "status", "label": "status", "datatype": "string", "editable": true, "active": false },
            { "name": "tags", "label": "tags", "datatype": "array", "editable": true, "active": false },
            { "name": "milestone", "label": "milestone", "datatype": "string", "editable": true, "active": false },
            { "name": "comments", "label": "comments", "datatype": "string", "editable": true, "active": false },
            { "name": "dateAdded", "label": "added", "datatype": "date", "editable": true, "active": false },
            { "name": "startDate", "label": "start", "datatype": "date", "editable": true, "active": false },
            { "name": "endDate", "label": "end", "datatype": "date", "editable": true, "active": false }
        ]

        this.columns = _.keyBy(this._possibleColumns, "name");
    }

    getAllTags() {
        var tags = [];
        _.each(this.tasks, function (item) {
            _.each(item.tags, function (tag) {
                if (tags.indexOf(tag) == -1) {
                    tags.push(tag);
                }
            })
        })

        tags.sort();

        return tags;
    }

    getAllStatus() {
        var status = [];
        _.each(this.tasks, function (task) {
            if (status.indexOf(task.status) == -1 && task.status != null) {
                status.push(task.status);
            }
        })

        status.sort();

        return status;
    }

    assignStrandedTasksToCurrentIsolationLevel() {
        var self = this;
        _.each(this.tasks, function (task) {
            if (task.parentTask == null && !task.isProjectRoot) {
                task.parentTask = self.idForIsolatedTask;
                self.tasks[self.idForIsolatedTask].childTasks.push(task.ID);
            }
        })
    }

    getProjectsInList() {
        var projects = [];
        _.each(this.tasks, function (task) {
            if (task.isProjectRoot) {
                projects.push(task);
            }
        })

        projects.sort();

        return projects;
    }

    getMilestones() {
        var projects = [];
        _.each(this.tasks, function (task) {
            if (projects.indexOf(task.milestone) == -1 && task.milestone != null) {
                projects.push(task.milestone);
            }
        })

        return projects;
    }

    getCrumbs() {
        //need to return these in top down order

        //get the isolation level, and work up through parents until there is none
        var crumbsOut = [];

        //return an array of tasks
        var bottomTask = this.tasks[this.idForIsolatedTask];

        while (bottomTask != null) {
            crumbsOut.unshift(bottomTask);

            if (bottomTask.parentTask == null) {
                bottomTask = null;
            } else {
                bottomTask = this.tasks[bottomTask.parentTask]
            }
        }

        return crumbsOut;
    }

    getGridDataObject() {
        var gridDataObject = {
            "metadata": _.filter(this.columns, "active"),
            "data": this._processGridData()
        };

        return gridDataObject;
    };

    _processGridData() {
        //get a list of all tasks
        //iterate through them
        //if they have a child... process the child next... same for that child
        //if they have a parent... skip and let the parent find them first

        //all tasks with either be at the root or have a parent
        //if at the root, add to the root, and process the child tasks, just push them on
        //do a depth first seach and all will get added

        var tasksOut = []

        //these checks set the sort column if used
        this.activeSortField = (this.isSortEnabled) ? this.sortField : "sortOrder";
        this.activeSortDir = (this.isSortEnabled) ? this.sortDir : "asc";

        //process the searchTerm
        //split on spaces, split on colon, build object
        //TODO split this out to get the search in a single place
        this.searchObj = this.searchTerm;
        var searchTextParts = this.searchTerm.split(" ");

        var self = this;

        _.each(searchTextParts, function (spaces) {
            if (spaces.indexOf(":") > -1) {
                var parts = spaces.split(":");

                if (typeof self.searchObj !== "object") {
                    self.searchObj = {};
                }
                self.searchObj[parts[0]] = parts[1];
            }
        })

        //run through children to update any dependent properties
        this.getPseudoRootNode().updateDependentProperties();

        //run the searches
        this.determineIfTasksAreVisible();

        //process children
        if (this.idForIsolatedTask == undefined) {
            this.recurseChildren(this.getPseudoRootNode(), -1, tasksOut)
        } else {
            //do the recursion only on the selected task
            var isolatedTask = this.tasks[this.idForIsolatedTask];
            //this will start at -1 (ignored) or 0 depending on flag.
            var startLevel = (this.hideRootIfIsolated) ? -1 : 0;
            this.recurseChildren(isolatedTask, startLevel, tasksOut);
        }

        //need to build tasksout down here based on the task visible option

        return _.map(tasksOut, function (item) {
            return { "id": item.ID, "values": item }
        })
    }

    determineIfTasksAreVisible() {
        //iterate each task and run the search
        var self = this;

        var tasksToProcessAgain = [];
        _.each(this.tasks, function (task) {
            var searchResult = self.searchTerm == "" || task.isResultForSearch(self.searchObj)
            var showBecauseComplete = (self.shouldHideComplete) ? !task.isComplete : true;
            var showBecauseNew = task.isFirstEdit;
            if ((searchResult && showBecauseComplete)||showBecauseNew) {

                tasksToProcessAgain.push(task);
                task.isVisible = true;
            } else {
                task.isVisible = false;
            }
        })

        _.each(tasksToProcessAgain, function (task) {
            if (self.searchChildren) {
                //add the kids
                function recurseMakeVisible(childTask) {
                    _.each(childTask.childTasks, function (childTaskID) {
                        recurseMakeVisible(self.tasks[childTaskID]);
                    })
                    childTask.isVisible = !childTask.isComplete;
                }

                recurseMakeVisible(task);
            }

            if (self.searchParents) {
                //add the parents
                //TODO rename the variables, this is awful
                var parentTaskId = task.parentTask;
                while (parentTaskId != null) {
                    var parentTask = self.tasks[parentTaskId]
                    parentTask.isVisible = !parentTask.isComplete;
                    parentTaskId = parentTask.parentTask;
                }
            }
        })
        //at this point, all of the tasks have visibility set
    }

    recurseChildren(task, indentLevel, tasksOut) {
        //skip if starting on the pseudo root
        if (indentLevel > -1) {
            //do a check on desc
            if (task.isVisible) {
                tasksOut.push(task);
            }
        }
        task.indent = indentLevel;
        var subProcessOrder = 0;

        //determine subtask ordering
        var self = this;
        var subOrder = _.map(task.childTasks, function (childTaskId) {
            return { "sort": self.tasks[childTaskId][self.activeSortField], "id": childTaskId }
        })

        subOrder = _.orderBy(subOrder, ["sort"], [this.activeSortDir])

        _.each(subOrder, function (itemObj) {
            var itemNo = itemObj.id;
            var childTask = self.tasks[itemNo];
            childTask.sortOrder = subProcessOrder++;
            self.recurseChildren(childTask, indentLevel + 1, tasksOut)
        });
    }

    getPseudoRootNode() {
        //need to return a "task" that has the parentless nodes as its children

        var newTask = new Task(this, false);

        _.each(this.tasks, function (task) {
            if (task.parentTask == null) {
                newTask.childTasks.push(task.ID)
            }
        })

        return newTask;
    }

    getNew() {
        var task = new Task(this);
        this.tasks[task.ID] = task;

        return task;
    }

    removeTask(ID) {
        //this will delete the task from the object

        //check if the task has a parent, if so remove from there
        var taskToDelete = this.tasks[ID];

        if (taskToDelete.parentTask != null) {
            //assign children to current parent
            var parentTask = this.tasks[taskToDelete.parentTask];
            parentTask.childTasks = parentTask.childTasks.concat(taskToDelete.childTasks);

            //find the index of the current task and splice it out
            var index = parentTask.childTasks.indexOf(ID);
            parentTask.childTasks.splice(index, 1);
        }

        //update parent of children to current parent
        var obj = this;
        _.each(taskToDelete.childTasks, function (taskId) {
            obj.tasks[taskId].parentTask = taskToDelete.parentTask;
        })

        //check if task has children, if so, delete those children too (and their children)
        // -or- collapse the current node "up" a level into the current parent

        delete this.tasks[ID];
    }

    getListOfColumns() {
        //this will return a list of all possible columns that could be visualized

        //iterate through possible columns and return the name
        return _.map(this._possibleColumns, "name");
    }

    getJSONString() {
        //TODO use this method for the normal save() call too
        var output = _.map(this.tasks, function (d) {
            return d.getObjectForSaving();
        })

        var objectToSave = {
            title: this.title,
            googleDriveId: this.googleDriveId,
            tasks: output
        };

        return JSON.stringify(objectToSave);
    }

    isDefaultList() {
        console.log(this.tasks)
        if (this.tasks[2].description == "new project") {
            if (Object.keys(this.tasks).length == 2 && this.tasks[3].description == "new task") {
                return true;
            }
            if (Object.keys(this.tasks).length == 1) {
                return true;
            }
        }

        return false;
    }

    save(callback) {
        var jsonfile = require("jsonfile");
        var _ = require("lodash");

        if (this.path == "") {
            //TODO put this prompt into a actual message bar
            console.log("no path set, will not save");
            return false;
        }

        //create new object with only the date to keep
        var output = _.map(this.tasks, function (d) {
            return d.getObjectForSaving();
        })

        var objectToSave = {
            title: this.title,
            googleDriveId: this.googleDriveId,
            tasks: output
        };

        jsonfile.writeFile(this.path, objectToSave, { spaces: 2 }, function (err) {
            if (err != null) {
                console.error(err);
            }

            //TODO change this out for a status update proper
            console.log("saved... calling callback");
            if (callback !== undefined) {
                callback();
            }
        })

        return true;
    }

    static createNewTaskList() {
        //create the new task list
        var list = new TaskList();

        //create a root task
        var rootTask = list.getNew();
        rootTask.isProjectRoot = true;
        rootTask.description = "new project";

        //isolate to the root task
        list.idForIsolatedTask = rootTask.ID;

        return list;
    }

    static load(path, callback, fileId) {
        var jsonfile = require("jsonfile");

        //create new object with only the date to keep
        var _ = require("lodash");

        var taskList = new TaskList();
        taskList.path = path;

        jsonfile.readFile(taskList.path, function (err, obj) {

            var dataObj = {};

            if (obj.length > 0) {
                //this is for the old format where the file was only tasks
                dataObj.tasks = obj;
            } else {
                //this loads an actual TaskList object
                dataObj = obj;
            }

            //obj contains title, googleDriveId, and tasks
            taskList.title = dataObj.title;
            if (fileId == undefined) {
                //try to get the data from the file
                taskList.googleDriveId = dataObj.googleDriveId;
            } else {
                //grab the fileId from Google
                taskList.googleDriveId = fileId;
            }

            _.each(dataObj.tasks, function (item) {
                var task = Task.createFromData(item, taskList);

                taskList.tasks[task.ID] = task;
            })

            //work is done, call the callback
            callback(taskList);
        })
    }
}

module.exports = TaskList;<|endoftext|>


<commit_before>module.exports = function() {
	var rabbit = require("../../src/index.js");

	// variable to hold starting time
	var started = Date.now();

	// variable to hold received count
	var received = 0;

	// expected message count
	var expected = 10000;

	// always setup your message handlers first

	// this handler will handle messages sent from the publisher
	rabbit.handle("#", function(msg) {
		console.log("LEFT Received:", JSON.stringify(msg.body), "routingKey:", msg.fields.routingKey);
		msg.ack();
		if ((++received) === expected) {
			console.log("LEFT Received", received, "messages after", (Date.now() - started), "milliseconds");
		}
	});

	// it can make a lot of sense to share topology definition across
	// services that will be using the same topology to avoid
	// scenarios where you have race conditions around when
	// exchanges, queues or bindings are in place
	require("./topology.js")(rabbit, "right", "left");

	console.log('Set up LEFT OK');
};<commit_msg>fix typo in channel binding<commit_after>module.exports = function() {
	var rabbit = require("../../src/index.js");

	// variable to hold starting time
	var started = Date.now();

	// variable to hold received count
	var received = 0;

	// expected message count
	var expected = 10000;

	// always setup your message handlers first

	// this handler will handle messages sent from the publisher
	rabbit.handle("#", function(msg) {
		console.log("LEFT Received:", JSON.stringify(msg.body), "routingKey:", msg.fields.routingKey);
		msg.ack();
		if ((++received) === expected) {
			console.log("LEFT Received", received, "messages after", (Date.now() - started), "milliseconds");
		}
	});

	// it can make a lot of sense to share topology definition across
	// services that will be using the same topology to avoid
	// scenarios where you have race conditions around when
	// exchanges, queues or bindings are in place
	require("./topology.js")(rabbit, "left", "left");

	console.log('Set up LEFT OK');
};<|endoftext|>


<commit_before>/**
 * MISSKEY BOOT LOADER
 * (ENTRY POINT)
 */

/**
 * ドメインに基づいて適切なスクリプトを読み込みます。
 * ユーザーの言語およびモバイル端末か否かも考慮します。
 */

'use strict';

// Get the current url information
const Url = new URL(location.href);

// Extarct the (sub) domain part of the current url
//
// e.g.
//   misskey.alice               => misskey
//   misskey.strawberry.pasta    => misskey
//   dev.misskey.alice.tachibana => dev
let app = Url.host.split('.')[0];

// Detect user language
// Note: The default language is English
let lang = navigator.language.split('-')[0];
if (!/^(en|ja)$/.test(lang)) lang = 'en';

// Detect user agent
const ua = navigator.userAgent.toLowerCase();
const isMobile = /mobile|iphone|ipad|android/.test(ua);

// Get the <head> element
const [head] = document.getElementsByTagName('head');

// If mobile, insert the viewport meta tag
if (isMobile) {
	const meta = document.createElement('meta');
	meta.setAttribute('name', 'viewport');
	meta.setAttribute('content', 'width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no');
	head.appendChild(meta);
}

// Switch desktop or mobile version
if (app == 'misskey') {
	app = isMobile ? 'mobile' : 'desktop';
}

// Load app script
// Note: 'async' makes can load the script async.
//       'defer' makes can run script when the dom loaded.
const script = document.createElement('script');
script.setAttribute('src', `/assets/${app}.${VERSION}.${lang}.js`);
script.setAttribute('async', 'true');
script.setAttribute('defer', 'true');
head.appendChild(script);
<commit_msg>Better English<commit_after>/**
 * MISSKEY BOOT LOADER
 * (ENTRY POINT)
 */

/**
 * ドメインに基づいて適切なスクリプトを読み込みます。
 * ユーザーの言語およびモバイル端末か否かも考慮します。
 */

'use strict';

// Get the current url information
const Url = new URL(location.href);

// Extarct the (sub) domain part of the current url
//
// e.g.
//   misskey.alice               => misskey
//   misskey.strawberry.pasta    => misskey
//   dev.misskey.alice.tachibana => dev
let app = Url.host.split('.')[0];

// Detect the user language
// Note: The default language is English
let lang = navigator.language.split('-')[0];
if (!/^(en|ja)$/.test(lang)) lang = 'en';

// Detect the user agent
const ua = navigator.userAgent.toLowerCase();
const isMobile = /mobile|iphone|ipad|android/.test(ua);

// Get the <head> element
const [head] = document.getElementsByTagName('head');

// If mobile, insert the viewport meta tag
if (isMobile) {
	const meta = document.createElement('meta');
	meta.setAttribute('name', 'viewport');
	meta.setAttribute('content', 'width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no');
	head.appendChild(meta);
}

// Switch desktop or mobile version
if (app == 'misskey') {
	app = isMobile ? 'mobile' : 'desktop';
}

// Load an app script
// Note: 'async' makes can load the script asyncly.
//       'defer' makes can run script when the dom loaded.
const script = document.createElement('script');
script.setAttribute('src', `/assets/${app}.${VERSION}.${lang}.js`);
script.setAttribute('async', 'true');
script.setAttribute('defer', 'true');
head.appendChild(script);
<|endoftext|>


<commit_before>'use strict';

/*
 * Controller for the contacts view with the listing of the device's contacts
 * Also, a factory wrapping ngCordova's contact plugin, which is a wrapper
 * around Cordova's contact plugin, which is a wrapper around the native
 * contacts API. Sweet!
 */

var contacts = angular.module('contacts', ['ngCordova', 'peerhandler'])
.controller('ContactsCtrl', function($scope, $localStorage, contactsFactory, peerFactory, socketFactory, $state, $ionicActionSheet, $translate) {

        var translations = null;

        var translations = $translate(['SAR_CALL', 'PROFILE', 'ACTIONS', 'CANCEL']).then(function (trans) {
            translations = trans;
        });

        contactsFactory.fetchAllContacts().then(function (results) {
            $scope.contacts = results;
        }).catch(function(err) {
            console.log(err);
        });

        socketFactory.registerCallback(socketFactory.eventTypes.CONTACT_ONLINE, function (data) {
            console.log('yupyupyup');
           $scope.contacts = contactsFactory.getContacts();
        });

        $scope.searchKeyPress = function(keyCode) {
            // Enter and Android keyboard 'GO' keycodes to close the keyboard
            if ((keyCode === 66 || keyCode === 13) && typeof cordova !== 'undefined') {
                cordova.plugins.Keyboard.close();
            }
        };

        $scope.user = $localStorage.user;

        $scope.selectUser = function(selectedUser) {

            var sheet = $ionicActionSheet.show({

                buttons: [
                    { text: ' ' + translations.SAR_CALL + '' },
                    { text: ' ' + translations.PROFILE },
                ],
                titleText:  translations.ACTIONS,
                cancelText: translations.CANCEL,
                cancel: function() {
                    sheet();
                },

                buttonClicked: function(index) {
                    switch (index) {
                        case 0:
                            peerFactory.callPeer(selectedUser);
                            break;
                        case 1:
                            $state.go('userprofile', { user: selectedUser });
                            break;
                    }
                    return true;
                }
            });
        };
});

contacts.factory('contactsFactory', function($cordovaContacts) {
    // Array to store all the devices contacts so we don't have to re-fetch them all the time
    var contacts = [];

    var contactStates = {
        BUSY:    "busy",
        OFFLINE: "offline",
        ONLINE:  "online"
    }

    return {
        contactStates: contactStates,

        fetchAllContacts: function() {
            // As far as I know, the fields do nothing. Cordova just YOLO's everything?
            var opts = {
                fields: ['id', 'displayName', 'name', 'phoneNumbers', 'emails', 'photos'],
                hasPhoneNumber : true
            };

            return $cordovaContacts.find(opts)
                .then(function (allContacts) {
                    //TODO: Maybe optimize this filter and format shebang a bit
                   var filtered =_.filter(allContacts, function(c) {
                       return (!(_.isEmpty(c.phoneNumbers)) &&  c.phoneNumbers.length > 0 )
                    });
                    var formatted = _.map(filtered, function(c) {
                        return {
                            "original": c,
                            "displayName": c.displayName || c.emails[0].value,
                            "number": c.phoneNumbers[0].value,
                            "photo": c.photos ? c.photos[0] ? c.photos[0].value : 'res/img/keilamies.png' : 'res/img/keilamies.png',
                            "currentState": contactStates.OFFLINE
                        }
                    });
                    contacts = formatted;
                    return formatted;
                  })
                .catch(function (err) {
                  return err;
           });
        },

        getContacts: function () {
            return contacts;
        },

        getContactByNumber(number) {
            return _.find(contacts, 'number', number);
        },
        setContactState(number, state) {
            var index = _.indexOf(contacts, this.getContactByNumber(number));

            if (index != -1) {
                console.log('setting contact ' + number + ' state to ' + state);
                contacts[index].currentState = state;
            }
        }
    };
});

<commit_msg>Working online state<commit_after>'use strict';

/*
 * Controller for the contacts view with the listing of the device's contacts
 * Also, a factory wrapping ngCordova's contact plugin, which is a wrapper
 * around Cordova's contact plugin, which is a wrapper around the native
 * contacts API. Sweet!
 */

var contacts = angular.module('contacts', ['ngCordova', 'peerhandler'])
.controller('ContactsCtrl', function($scope, $localStorage, contactsFactory, peerFactory, socketFactory, $state, $ionicActionSheet, $translate) {

        var translations = null;

        var translations = $translate(['SAR_CALL', 'PROFILE', 'ACTIONS', 'CANCEL']).then(function (trans) {
            translations = trans;
        });

        contactsFactory.fetchAllContacts().then(function (results) {
            $scope.contacts = results;
            console.log(results);
        }).catch(function(err) {
            console.log(err);
        });

        var updateContactState = function() {
            $scope.$apply(function () {
                $scope.contacts = contactsFactory.getContacts();
            });
        }

        socketFactory.registerCallback(socketFactory.eventTypes.CONTACT_ONLINE,  updateContactState);
        socketFactory.registerCallback(socketFactory.eventTypes.CONTACT_OFFLINE, updateContactState);

        $scope.searchKeyPress = function(keyCode) {
            // Enter and Android keyboard 'GO' keycodes to close the keyboard
            if ((keyCode === 66 || keyCode === 13) && typeof cordova !== 'undefined') {
                cordova.plugins.Keyboard.close();
            }
        };

        $scope.user = $localStorage.user;

        $scope.selectUser = function(selectedUser) {

            var sheet = $ionicActionSheet.show({

                buttons: [
                    { text: ' ' + translations.SAR_CALL + '' },
                    { text: ' ' + translations.PROFILE },
                ],
                titleText:  translations.ACTIONS,
                cancelText: translations.CANCEL,
                cancel: function() {
                    sheet();
                },

                buttonClicked: function(index) {
                    switch (index) {
                        case 0:
                            peerFactory.callPeer(selectedUser);
                            break;
                        case 1:
                            $state.go('userprofile', { user: selectedUser });
                            break;
                    }
                    return true;
                }
            });
        };
});

contacts.factory('contactsFactory', function($cordovaContacts) {
    // Array to store all the devices contacts so we don't have to re-fetch them all the time
    var contacts = [];

    var contactStates = {
        BUSY:    "busy",
        OFFLINE: "offline",
        ONLINE:  "online"
    }

    return {
        contactStates: contactStates,

        fetchAllContacts: function() {
            // As far as I know, the fields do nothing. Cordova just YOLO's everything?
            var opts = {
                fields: ['id', 'displayName', 'name', 'phoneNumbers', 'emails', 'photos'],
                hasPhoneNumber : true
            };

            return $cordovaContacts.find(opts)
                .then(function (allContacts) {
                    //TODO: Maybe optimize this filter and format shebang a bit
                   var filtered =_.filter(allContacts, function(c) {
                       return (!(_.isEmpty(c.phoneNumbers)) &&  c.phoneNumbers.length > 0 )
                    });
                    var formatted = _.map(filtered, function(c) {
                        return {
                            "original": c,
                            "displayName": c.displayName || c.emails[0].value,
                            "number": c.phoneNumbers[0].value,
                            "photo": c.photos ? c.photos[0] ? c.photos[0].value : 'res/img/keilamies.png' : 'res/img/keilamies.png',
                            "currentState": contactStates.OFFLINE
                        }
                    });
                    contacts = formatted;
                    return formatted;
                  })
                .catch(function (err) {
                  return err;
           });
        },

        getContacts: function () {
            return contacts;
        },

        getContactByNumber(number) {
            return _.find(contacts, 'number', number);
        },
        setContactState(number, state) {
            var index = _.indexOf(contacts, this.getContactByNumber(number));

            if (index != -1) {
                console.log('setting contact ' + number + ' state to ' + state);
                contacts[index].currentState = state;
            }
        }
    };
});

<|endoftext|>


<commit_before>angular.module('liturgieApp').controller('LiturgieController', function ($scope, $http, dbService, log) {

		$scope.validationRules = []
		$scope.onderdelen = [{ regel: "", class: "input-group", documents: [], icon: "fa-question" }]

		$http.get('./resources/validation.json').then(function (response) {
		for (n in response.data) {
			$scope.validationRules.push(response.data[n]);
		}
		});

		$scope.copyRawInput = function(rawInput) {
			if(rawInput == null || rawInput.trim().length == 0) {
				$scope.rawInputError = "Invoer is leeg, niets te doen"
				return;
			}
			$scope.rawInputError = ""
			// flush existing onderdelen
			$scope.onderdelen = []
			rawInputLines = rawInput.split("\n")
			for (index in rawInputLines) {
				if(rawInputLines[index].trim() == "") {
					continue
				}
				var onderdeel = {regel: ''}
				onderdeel.regel = rawInputLines[index]

				$scope.onderdelen.push({ regel: onderdeel.regel, class: "input-group", documents: [], icon: "fa-question" })
			}
			for (index in rawInputLines) {
				$scope.manageInputs(index, onderdeel)
			}
		}

		$scope.isValid = function (id) {
			var value = $scope.onderdelen[id].regel
			for (n in $scope.validationRules) {
				for (i in $scope.validationRules[n].regexen) {
					valid = new RegExp($scope.validationRules[n].regexen[i]).test(value)
					if (valid) {
						// gna gna, set the icon and the type here
						$scope.onderdelen[id].icon = $scope.validationRules[n].icon;
						$scope.onderdelen[id].getFromDb = $scope.validationRules[n].getFromDb
						return true;
					}
				}
			}
		}

		$scope.setOnderdeelDetails = function (index) {
			$scope.onderdelen[index].valid = true
		// get the regel. It will look like <book> <chapter> [:<verse>[<,|-><verse>]*]
		// examples:
		// psalm 2: 3, 6
		// gezang 45
		// 3 johannes 4:3 - 5
		// strip the regel from spaces
		var line = $scope.onderdelen[index].regel.trim()
		// log.debug('original: ' + line)

		// get the book. i.e. the part before the first space
		var book = line.match(/^([123 ]{0,2}[a-zA-Z0-9ëü]*)[ ]*.*$/)[1].trim()
		// log.debug('book: ' + book)

		// get the chapter. i.e. the word after the first space and before an optional :
		var chapter = -1
		try {
			chapter = line.match(/^[\d]?[ ]?[a-zA-Z0-9ëü]*[ ]+([0-9a-z]+)/)[1]
		} catch (error) {
			// line is no song or biblebook, hence it has no chapter
		}
		// log.debug('chapter: ' + chapter)

		// get first and last verse
		var verseLimits = { min: -1, max: -1 }
		try {
			verseLimits = { min: line.match(/: *([\d]+).*$/)[1], max: line.match(/(\d+)\D*$/)[1] }
		} catch (error) {
			// log.debug('verseLimits could not be determined; using defaults')
		}
		// log.debug('verseLimitMin: ' + verseLimits.min)
		// log.debug('verseLimitMax: ' + verseLimits.max)

		// get individual verses to know which ones to keep
		// split everything after the : on ,; if no , keep the one verse
		var keep = []
		if (line.indexOf(':') != -1) {
			var tmpKeep = line.match(/:(.*)/)[1]
			if (tmpKeep.indexOf(',') != -1) {
				keep = tmpKeep.split(',')
				// strip all entries from spaces
				keep = keep.map(Function.prototype.call, String.prototype.trim)
			} else {
				keep.push(tmpKeep)
			}
		}
		// log.debug('keep: ' + keep)

		// If the chapter == -1, it is most likely not a thingy in the database, so skip the search
		if($scope.onderdelen[index].getFromDb) {
			// get all documents from the chapter
			dbService.find({
				selector: { book: book, chapter: chapter }
				}).then(function (res) {
					// Update UI (almost) instantly
					$scope.onderdelen[index].documents = []
					if (res.docs.length == 0) {
						$scope.onderdelen[index].documents.push({ note: "Niets gevonden voor: " + $scope.onderdelen[index].regel })
					}
					else {
						// keep all documents
						if(keep.length == 0) {
							for (i in res.docs) {
								var currentDoc = res.docs[i]
								$scope.onderdelen[index].documents.push(currentDoc)
							}
						}
						// keep a subset of documents
						else {
							for (i in res.docs) {
								var currentDoc = res.docs[i]
								var keepIndex = keep.indexOf(currentDoc.verse)
								if (keepIndex > -1) {
									$scope.onderdelen[index].documents.push(currentDoc)
									keep.remove(currentDoc.verse)
									// log.debug(currentDoc)
								}
							}
							if (keep.length > 0) {
								// log.debug('some verses were not found: ' + keep)
								$scope.onderdelen[index].documents.push({ note: "De volgende verzen konden niet worden gevonden: " + keep })
							}
						}
					}
				}).catch(function (err) {
					log.error(err)
				}).finally(function () {
					$scope.got = true;
				});
			}
		}

		$scope.clearOnderdeelDetails = function (index) {
			$scope.onderdelen[index].valid = false
			$scope.onderdelen[index].documents = []
			$scope.onderdelen[index].icon = 'fa-question'
		}

		$scope.manageInputs = function (index, onderdeel) {

			// lege input toevoegen
			if (index == $scope.onderdelen.length - 1 && onderdeel.regel != '') {
				$scope.onderdelen.push({ regel: "", class: "input-group", documents: [], icon: "fa-question" })
			}

			// lege input verwijderen
			if (index == $scope.onderdelen.length - 2 && onderdeel.regel == '' && $scope.onderdelen[$scope.onderdelen.length - 1] == '') {
				$scope.onderdelen.pop()
			}

			// start validate current input
			if ($scope.isValid(index)) {
				$scope.setOnderdeelDetails(index);
				$scope.onderdelen[index].class = "input-group has-success"
			} else {
				$scope.clearOnderdeelDetails(index);
				$scope.onderdelen[index].class = "input-group has-error"
			}

			$scope.onderdelen[index].valid = valid;
			$scope.onderdelen[index].invalid = !valid;

		}

})
<commit_msg>fixed basic raw input<commit_after>angular.module('liturgieApp').controller('LiturgieController', function ($scope, $http, dbService, log) {

		$scope.validationRules = []
		$scope.onderdelen = [{ regel: "", class: "input-group", documents: [], icon: "fa-question" }]

		$http.get('./resources/validation.json').then(function (response) {
		for (n in response.data) {
			$scope.validationRules.push(response.data[n]);
		}
		});

		$scope.copyRawInput = function(rawInput) {
			if(rawInput == null || rawInput.trim().length == 0) {
				$scope.rawInputError = "Invoer is leeg, niets te doen"
				return;
			}
			$scope.rawInputError = ""
			// flush existing onderdelen
			$scope.onderdelen = []
			rawInputLines = rawInput.split("\n")
			for (index in rawInputLines) {
				if(rawInputLines[index].trim() == "") {
					continue
				}
				var onderdeel = {regel: ''}
				onderdeel.regel = rawInputLines[index]

				$scope.onderdelen.push({ regel: onderdeel.regel, class: "input-group", documents: [], icon: "fa-question" })
			}
			for (index in rawInputLines) {
				$scope.manageInputs(index, onderdeel)
			}
		}

		$scope.isValid = function (id) {
			var value = $scope.onderdelen[id].regel
			for (n in $scope.validationRules) {
				for (i in $scope.validationRules[n].regexen) {
					valid = new RegExp($scope.validationRules[n].regexen[i]).test(value)
					if (valid) {
						// gna gna, set the icon and the type here
						$scope.onderdelen[id].icon = $scope.validationRules[n].icon;
						$scope.onderdelen[id].getFromDb = $scope.validationRules[n].getFromDb
						return true;
					}
				}
			}
		}

		$scope.setOnderdeelDetails = function (index) {
			$scope.onderdelen[index].valid = true
		// get the regel. It will look like <book> <chapter> [:<verse>[<,|-><verse>]*]
		// examples:
		// psalm 2: 3, 6
		// gezang 45
		// 3 johannes 4:3 - 5
		// strip the regel from spaces
		var line = $scope.onderdelen[index].regel.trim()
		// log.debug('original: ' + line)

		// get the book. i.e. the part before the first space
		var book = line.match(/^([123 ]{0,2}[a-zA-Z0-9ëü]*)[ ]*.*$/)[1].trim()
		// log.debug('book: ' + book)

		// get the chapter. i.e. the word after the first space and before an optional :
		var chapter = -1
		try {
			chapter = line.match(/^[\d]?[ ]?[a-zA-Z0-9ëü]*[ ]+([0-9a-z]+)/)[1]
		} catch (error) {
			// line is no song or biblebook, hence it has no chapter
		}
		// log.debug('chapter: ' + chapter)

		// get first and last verse
		var verseLimits = { min: -1, max: -1 }
		try {
			verseLimits = { min: line.match(/: *([\d]+).*$/)[1], max: line.match(/(\d+)\D*$/)[1] }
		} catch (error) {
			// log.debug('verseLimits could not be determined; using defaults')
		}
		// log.debug('verseLimitMin: ' + verseLimits.min)
		// log.debug('verseLimitMax: ' + verseLimits.max)

		// get individual verses to know which ones to keep
		// split everything after the : on ,; if no , keep the one verse
		var keep = []
		if (line.indexOf(':') != -1) {
			var tmpKeep = line.match(/:(.*)/)[1]
			if (tmpKeep.indexOf(',') != -1) {
				keep = tmpKeep.split(',')
				// strip all entries from spaces
				keep = keep.map(Function.prototype.call, String.prototype.trim)
			} else {
				keep.push(tmpKeep)
			}
		}
		// log.debug('keep: ' + keep)

		// If the chapter == -1, it is most likely not a thingy in the database, so skip the search
		if($scope.onderdelen[index].getFromDb) {
			// get all documents from the chapter
			dbService.find({
				selector: { book: book, chapter: chapter }
				}).then(function (res) {
					// Update UI (almost) instantly
					$scope.onderdelen[index].documents = []
					if (res.docs.length == 0) {
						$scope.onderdelen[index].documents.push({ note: "Niets gevonden voor: " + $scope.onderdelen[index].regel })
					}
					else {
						// keep all documents
						if(keep.length == 0) {
							for (i in res.docs) {
								var currentDoc = res.docs[i]
								$scope.onderdelen[index].documents.push(currentDoc)
							}
						}
						// keep a subset of documents
						else {
							for (i in res.docs) {
								var currentDoc = res.docs[i]
								var keepIndex = keep.indexOf(currentDoc.verse)
								if (keepIndex > -1) {
									$scope.onderdelen[index].documents.push(currentDoc)
									keep.remove(currentDoc.verse)
									// log.debug(currentDoc)
								}
							}
							if (keep.length > 0) {
								// log.debug('some verses were not found: ' + keep)
								$scope.onderdelen[index].documents.push({ note: "De volgende verzen konden niet worden gevonden: " + keep })
							}
						}
					}
				}).catch(function (err) {
					log.error(err)
				}).finally(function () {
					$scope.got = true;
				});
			}
		}

		$scope.clearOnderdeelDetails = function (index) {
			$scope.onderdelen[index].valid = false
			$scope.onderdelen[index].documents = []
			$scope.onderdelen[index].icon = 'fa-question'
		}

		$scope.manageInputs = function (index, onderdeel) {

			if(index >= $scope.onderdelen.length) {
				log.warn('ignoring request to manage input with index ' + index + ' while onderdelen length is ' + $scope.onderdelen.length)
				return
			}

			// start validate current input
			if ($scope.isValid(index)) {
				$scope.setOnderdeelDetails(index);
				$scope.onderdelen[index].class = "input-group has-success"
			} else {
				$scope.clearOnderdeelDetails(index);
				$scope.onderdelen[index].class = "input-group has-error"
			}

			$scope.onderdelen[index].valid = valid;
			$scope.onderdelen[index].invalid = !valid;

			for(index = $scope.onderdelen.length - 1; index > 0; index--) {
				if($scope.onderdelen[index].regel.trim() == '') {
					$scope.onderdelen.pop()
				} else {
					break
				}
			}

			// add empty line at the end
			$scope.onderdelen.push({ regel: '', class: "input-group", documents: [], icon: "fa-question" })
		}

})
<|endoftext|>


<commit_before>(function(window) {
    'use strict';
    var Modulator = function(params) {

        if (!params)
            params = new Object();

        // this odd construct is for safari compatibility
        if (!("audioContext" in window))
            window.audioContext = new(window.AudioContext || window.webkitAudioContext)();

        if ("rate" in params)
            this.rate = params.rate;
        else
            this.rate = window.audioContext.sampleRate;

        this.encoder = new FskEncoder(this.rate);

        // Create a "script node" that will actually generate audio samples.
        this.script_node = Modulator.prototype.script_node;

        if (!this.script_node) {
            Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2);

            // If the script node has an invalid buffer size, force one with a nonzero buffer.
            if (!Modulator.prototype.script_node.bufferSize) {

                // IE with a polyfill exhibits this problem, and crashes when you try to stop.
                Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2);
                this.prototype.can_stop = false;
            }
            this.script_node = Modulator.prototype.script_node;
        }

        // Start out in a not-playing state
        this.playing = false;
    }

    Modulator.prototype = {
        audioCtx: null, // AudioContext object
        encoder: null, // FskEncoder object
        outputAudioBuffer: null, // AudioBuffer object
        uiCallback: null, // UI object for callback
        scriptNode: null, // Re-used script node object for audio generation
        can_stop: true, // Whether we can stop (usually we can)

        // modulate a single packet. The data to modulate should be Uint8 format
        // This function allocates an audio buffer based on the length of the data and the sample rate
        // It then calls the fsk modulator, and shoves the returned floating point array
        // into the audio context for later playback
        modulate: function(data) {
            var bufLen = Math.ceil(data.length * 8 * this.encoder.samplesPerBit());
            this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, this.rate);

            var timeStart = performance.now();

            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);
            this.encoder.modulate(data, outputFloatArray); // writes outputFloatArray in-place

            // How far into the outputAudioBuffer we are.
            this.script_node_offset = 0;

            var timeEnd = performance.now();
            var timeElapsed = timeEnd - timeStart;
            console.log("Rendered " + data.length + " data bytes in " +
                timeElapsed.toFixed(2) + "ms");
        },

        silence: function(msecs) {
            var bufLen = Math.ceil(window.audioContext.sampleRate / (1000.0 / msecs));
            this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, window.audioContext.sampleRate);
            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);
            for (var i = 0; i < outputFloatArray.length; i++)
                outputFloatArray[i] = 0;
            this.script_node_offset = 0;
        },

        // draw the waveform to the canvas, assuming the proper UI element is provided
        // for debug, of course
        drawWaveform: function(canvas) {
            // comment out now for performonce
            var b = this.outputAudioBuffer.getChannelData(0);
            this.drawWaveformToCanvas(b, 0, canvas);
        },

        processAudio: function(ev) {
            var outl = ev.outputBuffer.getChannelData(0);
            var outr = ev.outputBuffer.getChannelData(1);

            // If we're not playing, but still being called, just fill the channel with silence.
            if (!this.playing) {
                for (var i = 0; i < outl.length; i++)
                    outl[i] = outr[i] = 0;

                // Some browsers crash when you stop playing
                if (this.can_stop)
                    this.script_node.disconnect();
                return;
            }

            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);

            for (var i = 0; i < outl.length; i++) {
                if (this.script_node_offset >= outputFloatArray.length) {
                    // If there's more data to play, reset the output float array.
                    if (this.get_more_data())
                        outputFloatArray = this.outputAudioBuffer.getChannelData(0);

                    // Otherwise, fill the buffer with 0s, and we'll stop playing on the next iteration.
                    else {
                        for (var j = 0; j < outputFloatArray.length; j++)
                            outputFloatArray[j] = 0;
                    }
                    this.script_node_offset = 0;
                }

                outl[i] = outr[i] = outputFloatArray[this.script_node_offset++];
            }
        },

        // immediately play the modulated audio exactly once. Useful for debugging single packets
        playBuffer: function(obj, func) {
            console.log("-- playAudioBuffer --");
            var bufferNode = window.audioContext.createBufferSource();
            bufferNode.buffer = this.outputAudioBuffer;
            bufferNode.connect(window.audioContext.destination); // Connect to speakers
            bufferNode.addEventListener("ended", function() {
                var playTimeEnd = performance.now();
                var timeElapsed = playTimeEnd - this.playTimeStart;
                console.log("got audio ended event after " + timeElapsed.toFixed(2) + "ms");
                if (obj && func)
                    func.call(obj);
            }.bind(this));
            this.playTimeStart = performance.now();
            bufferNode.start(0); // play immediately
        },

        // Plays through an entire file. You need to set the callback so once
        // a single audio packet is finished, the next can start. The index
        // tells where to start playing. You could, in theory, start modulating
        // part-way through an audio stream by setting index to a higher number on your
        // first call.
        playLoop: function(obj, end_func, param) {

            this.get_more_data = function() {
                if (!end_func.call(obj, param)) {
                    this.playing = false;
                    return false;
                }
                return true;
            };

            this.script_node.onaudioprocess = function(ev) {
                Modulator.prototype.processAudio.call(this, ev);
            }.bind(this);

            if (!this.playing) {
                this.playing = true;
                this.script_node.connect(window.audioContext.destination);
            }
        },

        modulatePcm: function(data, type) {

            var bufLen = Math.ceil(data.length * 8 * this.encoder.samplesPerBit());
            var modulatedData = new Float32Array(bufLen);
            if (type === undefined)
                type = 16;

            var timeStart = 0;
            var timeEnd = 0;
            if ((typeof performance) === "object")
                timeStart = performance.now();
            this.encoder.modulate(data, modulatedData); // writes outputFloatArray in-place
            if ((typeof performance) === "object")
                timeEnd = performance.now();
            var timeElapsed = timeEnd - timeStart;
            console.log("Rendered " + data.length + " data bytes in " +
                timeElapsed.toFixed(2) + "ms");

            if (type === 16) {
                var pcmData = new Int16Array(modulatedData.length);
                for (var i = 0; i < modulatedData.length; i++) {
                    // Map -1 .. 1 to -32767 .. 32768
                    pcmData[i] = Math.round((modulatedData[i]) * 32767);
                }
                return pcmData;
            }
            else {
                var pcmData = new Uint8Array(new ArrayBuffer(modulatedData.length * 2));
                for (var i = 0; i < modulatedData.length; i++) {
                    // Map -1 .. 1 to -32767 .. 32768
                    var sample = Math.round((modulatedData[i]) * 32767);

                    // Javascript doesn't really do two's compliment
                    if (sample < 0)
                        sample = (0xffff - ~sample);

                    pcmData[(i * 2) + 0] = Math.round(sample) & 0xff;
                    pcmData[(i * 2) + 1] = Math.round(sample >> 8) & 0xff;
                }
                return pcmData;
            }
        },

        drawWaveformToCanvas: function(buffer, start, canvas) {
            if (!canvas || !canvas.getContext)
                return;

            var strip = canvas.getContext('2d');

            // Resize the canvas to be the window size.
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            var h = strip.canvas.height;
            var w = strip.canvas.width;
            strip.clearRect(0, 0, w, h);

            var y;
            // Draw scale lines at 10% interval
            strip.lineWidth = 1.0;
            strip.strokeStyle = "#55a";
            strip.beginPath();
            y = 1 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 2 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 3 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 4 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 5 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 6 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 7 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 8 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 9 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            strip.stroke();

            strip.strokeStyle = "#fff";
            strip.lineWidth = 1.0;

            var b = start;
            var lastSample = (buffer[b++] + 1) / 2; // map -1..1 to 0..1

            for (var x = 1; x < canvas.width; x++) {
                var sample = (buffer[b++] + 1) / 2;
                if (b > buffer.length)
                    break;
                strip.beginPath();
                strip.moveTo(x - 1, h - lastSample * h);
                strip.lineTo(x, h - sample * h);
                strip.stroke();
                lastSample = sample;
            }
        }
    };

    /* Set up the constructor, so we can do "new Modulator()" */
    window.Modulator = function(params) {
        return new Modulator(params);
    };
}(this));<commit_msg>modulate: move webaudio code out of constructor<commit_after>(function(window) {
    'use strict';
    var Modulator = function(params) {

        if (!params)
            params = new Object();

        if ("rate" in params)
            this.rate = params.rate;

        this.encoder = new FskEncoder(this.rate);

        // Create a "script node" that will actually generate audio samples.
        this.script_node = Modulator.prototype.script_node;

        // Start out in a not-playing state
        this.playing = false;
    }

    Modulator.prototype = {
        encoder: null, // FskEncoder object
        outputAudioBuffer: null, // AudioBuffer object
        uiCallback: null, // UI object for callback
        scriptNode: null, // Re-used script node object for audio generation
        can_stop: true, // Whether we can stop (usually we can)

        // modulate a single packet. The data to modulate should be Uint8 format
        // This function allocates an audio buffer based on the length of the data and the sample rate
        // It then calls the fsk modulator, and shoves the returned floating point array
        // into the audio context for later playback
        modulateStream: function(data) {

            // this odd construct is for safari compatibility
            if (!("audioContext" in window))
                window.audioContext = new(window.AudioContext || window.webkitAudioContext)();

            if (!"rate" in this)
                this.rate = window.audioContext.sampleRate;

            if (!this.script_node) {
                Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2);

                // If the script node has an invalid buffer size, force one with a nonzero buffer.
                if (!Modulator.prototype.script_node.bufferSize) {

                    // IE with a polyfill exhibits this problem, and crashes when you try to stop.
                    Modulator.prototype.script_node = window.audioContext.createScriptProcessor(4096, 2, 2);
                    this.prototype.can_stop = false;
                }
                this.script_node = Modulator.prototype.script_node;
            }

            var bufLen = Math.ceil(data.length * 8 * this.encoder.samplesPerBit());
            this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, this.rate);

            var timeStart = performance.now();

            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);
            this.encoder.modulate(data, outputFloatArray); // writes outputFloatArray in-place

            // How far into the outputAudioBuffer we are.
            this.script_node_offset = 0;

            var timeEnd = performance.now();
            var timeElapsed = timeEnd - timeStart;
            console.log("Rendered " + data.length + " data bytes in " +
                timeElapsed.toFixed(2) + "ms");
        },

        silence: function(msecs) {
            var bufLen = Math.ceil(window.audioContext.sampleRate / (1000.0 / msecs));
            this.outputAudioBuffer = window.audioContext.createBuffer(1, bufLen, window.audioContext.sampleRate);
            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);
            for (var i = 0; i < outputFloatArray.length; i++)
                outputFloatArray[i] = 0;
            this.script_node_offset = 0;
        },

        // draw the waveform to the canvas, assuming the proper UI element is provided
        // for debug, of course
        drawWaveform: function(canvas) {
            // comment out now for performonce
            var b = this.outputAudioBuffer.getChannelData(0);
            this.drawWaveformToCanvas(b, 0, canvas);
        },

        processAudio: function(ev) {
            var outl = ev.outputBuffer.getChannelData(0);
            var outr = ev.outputBuffer.getChannelData(1);

            // If we're not playing, but still being called, just fill the channel with silence.
            if (!this.playing) {
                for (var i = 0; i < outl.length; i++)
                    outl[i] = outr[i] = 0;

                // Some browsers crash when you stop playing
                if (this.can_stop)
                    this.script_node.disconnect();
                return;
            }

            var outputFloatArray = this.outputAudioBuffer.getChannelData(0);

            for (var i = 0; i < outl.length; i++) {
                if (this.script_node_offset >= outputFloatArray.length) {
                    // If there's more data to play, reset the output float array.
                    if (this.get_more_data())
                        outputFloatArray = this.outputAudioBuffer.getChannelData(0);

                    // Otherwise, fill the buffer with 0s, and we'll stop playing on the next iteration.
                    else {
                        for (var j = 0; j < outputFloatArray.length; j++)
                            outputFloatArray[j] = 0;
                    }
                    this.script_node_offset = 0;
                }

                outl[i] = outr[i] = outputFloatArray[this.script_node_offset++];
            }
        },

        // immediately play the modulated audio exactly once. Useful for debugging single packets
        playBuffer: function(obj, func) {
            console.log("-- playAudioBuffer --");
            var bufferNode = window.audioContext.createBufferSource();
            bufferNode.buffer = this.outputAudioBuffer;
            bufferNode.connect(window.audioContext.destination); // Connect to speakers
            bufferNode.addEventListener("ended", function() {
                var playTimeEnd = performance.now();
                var timeElapsed = playTimeEnd - this.playTimeStart;
                console.log("got audio ended event after " + timeElapsed.toFixed(2) + "ms");
                if (obj && func)
                    func.call(obj);
            }.bind(this));
            this.playTimeStart = performance.now();
            bufferNode.start(0); // play immediately
        },

        // Plays through an entire file. You need to set the callback so once
        // a single audio packet is finished, the next can start. The index
        // tells where to start playing. You could, in theory, start modulating
        // part-way through an audio stream by setting index to a higher number on your
        // first call.
        playLoop: function(obj, end_func, param) {

            this.get_more_data = function() {
                if (!end_func.call(obj, param)) {
                    this.playing = false;
                    return false;
                }
                return true;
            };

            this.script_node.onaudioprocess = function(ev) {
                Modulator.prototype.processAudio.call(this, ev);
            }.bind(this);

            if (!this.playing) {
                this.playing = true;
                this.script_node.connect(window.audioContext.destination);
            }
        },

        modulatePcm: function(data, type) {

            var bufLen = Math.ceil(data.length * 8 * this.encoder.samplesPerBit());
            var modulatedData = new Float32Array(bufLen);
            if (type === undefined)
                type = 16;

            var timeStart = 0;
            var timeEnd = 0;
            if ((typeof performance) === "object")
                timeStart = performance.now();
            this.encoder.modulate(data, modulatedData); // writes outputFloatArray in-place
            if ((typeof performance) === "object")
                timeEnd = performance.now();
            var timeElapsed = timeEnd - timeStart;
            console.log("Rendered " + data.length + " data bytes in " +
                timeElapsed.toFixed(2) + "ms");

            if (type === 16) {
                var pcmData = new Int16Array(modulatedData.length);
                for (var i = 0; i < modulatedData.length; i++) {
                    // Map -1 .. 1 to -32767 .. 32768
                    pcmData[i] = Math.round((modulatedData[i]) * 32767);
                }
                return pcmData;
            }
            else {
                var pcmData = new Uint8Array(new ArrayBuffer(modulatedData.length * 2));
                for (var i = 0; i < modulatedData.length; i++) {
                    // Map -1 .. 1 to -32767 .. 32768
                    var sample = Math.round((modulatedData[i]) * 32767);

                    // Javascript doesn't really do two's compliment
                    if (sample < 0)
                        sample = (0xffff - ~sample);

                    pcmData[(i * 2) + 0] = Math.round(sample) & 0xff;
                    pcmData[(i * 2) + 1] = Math.round(sample >> 8) & 0xff;
                }
                return pcmData;
            }
        },

        drawWaveformToCanvas: function(buffer, start, canvas) {
            if (!canvas || !canvas.getContext)
                return;

            var strip = canvas.getContext('2d');

            // Resize the canvas to be the window size.
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            var h = strip.canvas.height;
            var w = strip.canvas.width;
            strip.clearRect(0, 0, w, h);

            var y;
            // Draw scale lines at 10% interval
            strip.lineWidth = 1.0;
            strip.strokeStyle = "#55a";
            strip.beginPath();
            y = 1 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 2 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 3 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 4 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 5 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 6 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 7 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 8 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            y = 9 * (h / 10);
            strip.moveTo(0, y);
            strip.lineTo(w, y);
            strip.stroke();

            strip.strokeStyle = "#fff";
            strip.lineWidth = 1.0;

            var b = start;
            var lastSample = (buffer[b++] + 1) / 2; // map -1..1 to 0..1

            for (var x = 1; x < canvas.width; x++) {
                var sample = (buffer[b++] + 1) / 2;
                if (b > buffer.length)
                    break;
                strip.beginPath();
                strip.moveTo(x - 1, h - lastSample * h);
                strip.lineTo(x, h - sample * h);
                strip.stroke();
                lastSample = sample;
            }
        }
    };

    /* Set up the constructor, so we can do "new Modulator()" */
    window.Modulator = function(params) {
        return new Modulator(params);
    };
}(this));<|endoftext|>


<commit_before>/**
 * This module provides core functions.
 */
mol.modules.core = function(mol) {

    mol.core = {};

    //'layer-{0}-{1}'.format(name.replace(/ /g,"_"), type.replace(/ /g,"_")));

    /**
     * Retunrs a layer id string given a layer {name, type, source}.
     */
    mol.core.getLayerId = function(layer) {
        var name = layer.name.trim().replace(/ /g, "_"),
            type = layer.type.trim().replace(/ /g, "_"),
            source = layer.source.trim().replace(/ /g, "_");

        return 'layer-{0}-{1}-{2}'.format(name, type, source);
    };

    /**
     * @param id The layer id of the form "layer-{name}-{type}-{source}".
     */
    mol.core.getLayerFromId = function(id) {
        var tokens = id.split('-'),
            name = tokens[1].replace(/_/g, " "),
            type = tokens[2].replace(/_/g, " "),
            source = tokens[3].replace(/_/g, " ");

        return {
            id: id,
            name: name,
            type: type,
            souce: source
        };
    };
};
<commit_msg>Remove unused code.<commit_after>/**
 * This module provides core functions.
 */
mol.modules.core = function(mol) {

    mol.core = {};

    /**
     * Retunrs a layer id string given a layer {name, type, source}.
     */
    mol.core.getLayerId = function(layer) {
        var name = layer.name.trim().replace(/ /g, "_"),
            type = layer.type.trim().replace(/ /g, "_"),
            source = layer.source.trim().replace(/ /g, "_");

        return 'layer-{0}-{1}-{2}'.format(name, type, source);
    };

    /**
     * @param id The layer id of the form "layer-{name}-{type}-{source}".
     */
    mol.core.getLayerFromId = function(id) {
        var tokens = id.split('-'),
            name = tokens[1].replace(/_/g, " "),
            type = tokens[2].replace(/_/g, " "),
            source = tokens[3].replace(/_/g, " ");

        return {
            id: id,
            name: name,
            type: type,
            souce: source
        };
    };
};
<|endoftext|>


<commit_before>'use strict';

angular.module('baikalApp.services', ['ngResource'])

.factory('Photos', ['$resource',
  function($resource){
    return $resource('photo/:season.json', {}, {});
  }])

.factory('Music', ['$resource',
  function($resource){
    var Music = {state: 0 /* 0 - pause, 1 - play, 2 - loading */, current: 0};
    Music.list = $resource('music/list.json', {}, {}).query(function() {
      for (var i = Music.list.length - 1; i >= 0; i--) {
        Music.list[i].id = i;
      };
      document.getElementById('audio_mp3').src = Music.list[0].mp3;
      document.getElementById('audio_ogg').src = Music.list[0].ogg;
      jQuery('#audio_audio').load().bind('ended', function(){
          Music.playNext();
      })
      .bind('playing', function(){
          console.log(Music.state+' -> 1');
          Music.state = 1;
          console.log(Music.state+' new value');
      })
      .bind('pause', function(){
        console.log(Music.state+' -> 0');
          Music.state = 0;
          console.log(Music.state+' new value');
      })
      .bind('waiting', function(){
        console.log(Music.state+' -> 2');
          Music.state = 2;
          console.log(Music.state+' new value');
      });
    });

    Music.playPause = function(id) {
      if (typeof id == 'undefined' || id == Music.current) {
        if (Music.state == 1) {
          document.getElementById('audio_audio').pause();
        } else {
          document.getElementById('audio_audio').play();
        }
      } else {
        Music.play(id);
      }
    }

    Music.play = function(id) {
      Music.current = id;
      document.getElementById('audio_mp3').src = Music.list[Music.current].mp3;
      document.getElementById('audio_ogg').src = Music.list[Music.current].ogg;
      jQuery('#audio_audio').load();
      document.getElementById('audio_audio').play();
    }

    Music.playNext = function() {
      Music.play((Music.current + 1) % Music.list.length);
    }

    return Music;
  }])

.factory('Post', ['$resource',
  function($resource){
    return $resource('post/:cid/:pid.json', {}, {});
  }])

.factory('Category', ['$resource',
  function($resource){
    return $resource('post/categories.json', {}, {});
  }])

.factory('Media', ['$resource',
  function($resource){
    return $resource('media/:pid.json', {}, {});
  }]);<commit_msg>music<commit_after>'use strict';

angular.module('baikalApp.services', ['ngResource'])

.factory('Photos', ['$resource',
  function($resource){
    return $resource('photo/:season.json', {}, {});
  }])

.factory('Music', ['$resource',
  function($resource){
    var Music = {state: 0 /* 0 - pause, 1 - play, 2 - loading */, current: 0};
    Music.list = $resource('music/list.json', {}, {}).query(function() {
      for (var i = Music.list.length - 1; i >= 0; i--) {
        Music.list[i].id = i;
      };
      document.getElementById('audio_mp3').src = Music.list[0].mp3;
      document.getElementById('audio_ogg').src = Music.list[0].ogg;
      jQuery('#audio_audio').load().bind('ended', function(){
          Music.playNext();
      })
      .bind('playing', function(){
          console.log(Music.state+' -> 1');
          Music.updateState(1);
          console.log(Music.state+' new value');
      })
      .bind('pause', function(){
        console.log(Music.state+' -> 0');
          Music.updateState(0);
          console.log(Music.state+' new value');
      })
      .bind('waiting', function(){
        console.log(Music.state+' -> 2');
          Music.updateState(2);
          console.log(Music.state+' new value');
      });
    });

    Music.updateState = function(state) {
      Music.state = state;
    }

    Music.playPause = function(id) {
      if (typeof id == 'undefined' || id == Music.current) {
        if (Music.state == 1) {
          document.getElementById('audio_audio').pause();
        } else {
          document.getElementById('audio_audio').play();
        }
      } else {
        Music.play(id);
      }
    }

    Music.play = function(id) {
      Music.current = id;
      document.getElementById('audio_mp3').src = Music.list[Music.current].mp3;
      document.getElementById('audio_ogg').src = Music.list[Music.current].ogg;
      jQuery('#audio_audio').load();
      document.getElementById('audio_audio').play();
    }

    Music.playNext = function() {
      Music.play((Music.current + 1) % Music.list.length);
    }

    return Music;
  }])

.factory('Post', ['$resource',
  function($resource){
    return $resource('post/:cid/:pid.json', {}, {});
  }])

.factory('Category', ['$resource',
  function($resource){
    return $resource('post/categories.json', {}, {});
  }])

.factory('Media', ['$resource',
  function($resource){
    return $resource('media/:pid.json', {}, {});
  }]);<|endoftext|>


<commit_before>'use strict';

/* Services */

angular.module('myApp.services', [])
.value('FIREBASE_URL', 'https://waitand-eat.firebaseio.com/')

.factory('dataService', function($firebase, FIREBASE_URL) {
	var dataRef = new Firebase(FIREBASE_URL);
	var fireData = $firebase(dataRef);

	return fireData;
})

.factory('partyService', function(dataService) {
		var users = dataService.$child('users');

		var partyServiceObject = {
			saveParty: function(party, userId) {
				users.$child(userId).$child('parties').$add(party);
			},
			getPartyByUserId: function(userId) {
				return users.$child(userId).$child('parties');
			}
		};

		return partyServiceObject;
})

.factory('textMessageService', function(partyService, dataService) {
	var textMessages = dataService.$child('textMessages');

	var textMessageServiceObject = {
		sendTextMessage: function(party) {
			var newTextMessage = {
				phoneNumber: party.phone,
				size: party.size,
				name: party.name
			};
			textMessages.$add(newTextMessage);
			party.notified = "Yes";
			// $scope.parties.$save(party.$id)
			partyService.parties.$save(party.$id);
		}
	};

	return textMessageServiceObject;
})

.factory('authService', function($firebaseSimpleLogin, $location, $rootScope, FIREBASE_URL) {
	var authRef = new Firebase(FIREBASE_URL);
	var auth = $firebaseSimpleLogin(authRef);

	var authServiceObject =  {
		register: function(user) {
			auth.$createUser(user.email, user.password)
			.then(function(data) {
				console.log(data);
				authServiceObject.login(user);
			});
		},
		login: function(user) {
			auth.$login('password', user)
			.then(function(data) {
				console.log(data);
				$location.path('/waitlist');
			});
		},
		logout: function() {
			auth.$logout();
			$location.path('/');
		},
		getCurrentUser: function() {
			return auth.$getCurrentUser();
		}
	};

	$rootScope.$on("$firebaseSimpleLogin:login", function(e, user) {
		$rootScope.currentUser = user;
	});

	$rootScope.$on("$firebaseSimpleLogin:logout", function() {
		$rootScope.currentUser = null;
	});

	return authServiceObject;
});

<commit_msg>fixed bug<commit_after>'use strict';

/* Services */

angular.module('myApp.services', [])
.value('FIREBASE_URL', 'https://waitand-eat.firebaseio.com/')

.factory('dataService', function($firebase, FIREBASE_URL) {
	var dataRef = new Firebase(FIREBASE_URL);
	var fireData = $firebase(dataRef);

	return fireData;
})

.factory('partyService', function(dataService) {
		var users = dataService.$child('users');

		var partyServiceObject = {
			saveParty: function(party, userId) {
				users.$child(userId).$child('parties').$add(party);
			},
			getPartiesByUserId: function(userId) {
				return users.$child(userId).$child('parties');
			}
		};

		return partyServiceObject;
})

.factory('textMessageService', function(dataService, partyService) {
	var textMessages = dataService.$child('textMessages');

	var textMessageServiceObject = {
		sendTextMessage: function(party) {
			var newTextMessage = {
				phoneNumber: party.phone,
				size: party.size,
				name: party.name
			};
			textMessages.$add(newTextMessage);
			party.notified = "Yes";
			partyService.parties.$save(party.$id);
		}
	};

	return textMessageServiceObject;
})

.factory('authService', function($firebaseSimpleLogin, $location, $rootScope, FIREBASE_URL) {
	var authRef = new Firebase(FIREBASE_URL);
	var auth = $firebaseSimpleLogin(authRef);

	var authServiceObject =  {
		register: function(user) {
			auth.$createUser(user.email, user.password)
			.then(function(data) {
				console.log(data);
				authServiceObject.login(user);
			});
		},
		login: function(user) {
			auth.$login('password', user)
			.then(function(data) {
				console.log(data);
				$location.path('/waitlist');
			});
		},
		logout: function() {
			auth.$logout();
			$location.path('/');
		},
		getCurrentUser: function() {
			return auth.$getCurrentUser();
		}
	};

	$rootScope.$on('$firebaseSimpleLogin:login', function(e, user) {
		$rootScope.currentUser = user;
	});

	$rootScope.$on('$firebaseSimpleLogin:logout', function() {
		$rootScope.currentUser = null;
	});

	return authServiceObject;
});

<|endoftext|>


<commit_before>/* settings.js

	Settings object for the game.
*/

(function(sys) {

"use strict";

// Define settings
var settings = {};

// Game manager settings.
settings.gm = {
	// Frames per second.
	fps: 60
};

// Game board settings.
settings.board = {
	columns: 32,
	rows: 24
};

// Snake settings.
settings.snake = {
	// Snake slot movements per second.
	speed: 5,
	startLength: 15,
	startCol: 15,
	startRow: 16,
	startDirection: "right",
	width: 16,
	color: "#000000"
};

sys.g.settings = settings;

})(jsnake);
<commit_msg>Changed snake speed to 8<commit_after>/* settings.js

	Settings object for the game.
*/

(function(sys) {

"use strict";

// Define settings
var settings = {};

// Game manager settings.
settings.gm = {
	// Frames per second.
	fps: 60
};

// Game board settings.
settings.board = {
	columns: 32,
	rows: 24
};

// Snake settings.
settings.snake = {
	// Snake slot movements per second.
	speed: 8,
	startLength: 15,
	startCol: 15,
	startRow: 16,
	startDirection: "right",
	width: 16,
	color: "#000000"
};

sys.g.settings = settings;

})(jsnake);
<|endoftext|>